﻿using DevComponents.AdvTree;
using DevComponents.DotNetBar;
using DevComponents.DotNetBar.SuperGrid;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
//using PlanningGIS.Access;
using PlanningGIS.ArcGIS;
using PlanningGIS.ArcGIS.Custom;
using PlanningGIS.DataConvert.form;
using PlanningGIS.DataConvert.model;
using PlanningGIS.Engine.Controls;
using PlanningGIS.Framework;
using PlanningGIS.Framework.Config;
using PlanningGIS.Framework.Controls;
using PlanningGIS.Framework.Rule;
using PlanningGIS.MapSheet;
using PlanningGIS.Util;
using PlanningGIS.Util.Collections;
using PlanningGIS.Util.Convertor;
using PlanningGIS.Util.Data;
using PlanningGIS.Util.Log;
using PlanningGIS.Util.Win32;
using PlanningGIS.Win.Controls;

namespace PlanningGIS.DataConvert
{
    /// <summary>
    /// 矢量数据导出界面
    /// </summary>
    public partial class FrmDlgDataExportNew :Office2007Form
    {
        /// <summary>
        /// 
        /// </summary>
        private IMap m_pMap;
        /// <summary>
        /// 
        /// </summary>
        private IApplication m_Application = null;

        /// <summary>
        /// 总进度条
        /// </summary>
        public Progressor ProgressAll;

        /// <summary>
        /// 分进度条
        /// </summary>
        public Progressor ProgressSub;

        /// <summary>
        /// 自定义导出范围图形
        /// </summary>
        private IPolygon pPolygonCustom;
        /// <summary>
        /// 按测区范围
        /// </summary>
        private IPolygon pPolygonSurvey;
        /// <summary>
        /// 
        /// </summary>
        private IElement m_pElementUserDraw;
        /// <summary>
        /// 
        /// </summary>
        private DlgDataExportConstruct dlgDataExportConstruct;
        /// <summary>
        /// 
        /// </summary>
        private DlgDataExport dlgDataExport;
        ///// <summary>
        ///// 是否正在导出中
        ///// </summary>
        //private bool doing = false;

        /// <summary>
        /// 是否为终止状态
        /// </summary>
        private bool breaked = true;
        /// <summary>
        /// 实现窗体的单态，每次弹出的窗口都为同一个
        /// </summary>
        private static FrmDlgDataExportNew dlgDataExportForm;
        /// <summary>
        /// 树动
        /// </summary>
        private bool tree = false;
        /// <summary>
        /// 表动
        /// </summary>
        private bool grid = false;
        /// <summary>
        /// 
        /// </summary>
        private string ruleName;

        /// <summary>
        /// 地图关联对象
        /// </summary>
        private IHookHelper m_HookHelp = null;

        /// <summary>
        /// 打开范围面
        /// </summary>
        private OpenDataDialog frmAddData = new OpenDataDialog();
        /// <summary>
        /// 地图关联对象
        /// </summary>
        
        /// <summary>
        /// 导出CAD操作
        /// </summary>
        private ExportCAD _Export = null;
        
        public object Hook
        {
            set
            {
                m_HookHelp = new HookHelper();
                m_HookHelp.Hook = value;
            }
        }
        /// <summary>
        /// 绘制工具构建对象
        /// </summary>
        private ToolCreator _ToolCreator = null;

        /// <summary>
        /// 结合表选择构建对象
        /// </summary>
        private SheetCreator _SheetCreator = null;

        /// <summary>
        /// 测区选择构建对象
        /// </summary>
        private AreaCreator _AreaCreator = null;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="value"></param>
        public FrmDlgDataExportNew(IApplication value)
        {
            InitializeComponent();
            m_Application = value;
            if (m_Application != null && (m_Application.Document as IMxDocument ).ActiveView.FocusMap !=null)
            {
                m_pMap = (m_Application.Document as IMxDocument).ActiveView.FocusMap;
            }
            m_HookHelp = new HookHelper();
            m_HookHelp.Hook = (value as IFramework).Object;
            Init();
        }

        /// <summary>
        /// 初始化对象
        /// </summary>
        private void Init()
        {
            _SheetCreator = new SheetCreator(spgrdSheet,false);
            _SheetCreator.Hook = m_HookHelp.Hook;
            _SheetCreator.IsToMap = true;

            _AreaCreator = new AreaCreator(spgrdArea);
            _AreaCreator.Hook = m_HookHelp.Hook;

            List<ValueName> btns = new List<ValueName>()
            {
                new ValueName(){Value="ToolDrawRectangle",Name="绘制矩形"},
                new ValueName(){Value="ToolDrawPolygon",Name="绘制多边形"},
                new ValueName(){Value="ToolDrawCircle",Name="绘制圆"},
                new ValueName(){Value="ToolDrawLine",Name="绘制线"}
            };
            _ToolCreator = new ToolCreator(btnDrawExtent, m_HookHelp.Hook);
            _ToolCreator.HideForm = true;
            _ToolCreator.Create(btns, true);
            _ToolCreator.DrawFinished += OnDrawFinished;
            regionTree.Hook = m_HookHelp.Hook;
            if (JHBHelper.ScaleValues != null)
            {
                foreach (int scale in JHBHelper.ScaleValues)
                {
                    //this.cmbScale1.Items.Add(scale.ToString());
                    this.cmbScale.Items.Add(scale.ToString());
                }
            }
            if (cmbScale.Items.Count > 0)
            {
                this.cmbScale.SelectedIndex = 0;
            }
            cboType.SelectedIndex = 0;

            SuperTabItem tim = this.sptbitmArea;
        }

        /// <summary>
        /// 绘制完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnDrawFinished(object sender, DrawArgs e)
        {
            if (sptbctlGeo.SelectedTab == sptbitmRegion)
                regionTree.SelectRegion(e.Geometry, e.Shift);
            else if (sptbctlGeo.SelectedTab == sptbitmSheet)
                _SheetCreator.SelectRegion(e.Geometry, e.Shift);
            
        }
        /// <summary>
        /// 获取单态对象
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static FrmDlgDataExportNew GetDlgExportForm(IApplication value)
        {
            if (dlgDataExportForm == null)
            {
                dlgDataExportForm = new FrmDlgDataExportNew(value);
            }
            return dlgDataExportForm;
        }

        #region 事件

        private void FrmDlgDataExportNew_Load(object sender, EventArgs e)
        {
            frmAddData = new OpenDataDialog();
            frmAddData.OnOkClick = new EventHandler(btnAddData_Click);
            frmAddData.MultiSelect = false;
            
            dataGridViewByMap.ColumnHeaderMouseClick += ControlHelper.dataGridViewX_ColumnHeaderMouseClick;
            //刷新按地图导出树控件
            RefreshCurMapLayer();
            FrameworkHelper.ShowLogPanel();

            #region ToolTips
            SuperTooltip spttUseGP = new SuperTooltip();
            spttUseGP.SetSuperTooltip(this.chkUseGP,
                new SuperTooltipInfo("利用GP工具进行导出，速度较快，但日志和进度条不够详细，且仅支持导出格式为SHP、MDB和GDB。\r\n注意：同一个要素类只能被导出一次！", "", "", null, null, eTooltipColor.Office2003));

            SuperTooltip spttDelNull = new SuperTooltip();
            spttDelNull.SetSuperTooltip(this.chkDelNullData,
                new SuperTooltipInfo("导出完毕后，自动删除无要素图层，且仅支持导出格式为SHP、MDB和GDB。", "", "", null, null, eTooltipColor.Office2003));

            SuperTooltip spttCut = new SuperTooltip();
            spttCut.SetSuperTooltip(this.chkCut,
                new SuperTooltipInfo("按照范围边线对超出范围的数据进行裁切。", "", "", null, null, eTooltipColor.Office2003));
            #endregion

        }
        /// <summary>
        /// 窗体关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmDlgDataExport_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!(m_Application as IFramework).IsMapCtrlactive)
            {
                MsgHelper.ShowInfomationMsgbox("请先切换到数据视图再进行此操作！");
                e.Cancel = true;
            }

            if (!breaked)
            {
                MsgHelper.ShowInfomationMsgbox("导出还未结束，不能退出该窗口！");
                e.Cancel = true;
            }
        }
        /// <summary>
        /// 窗体关闭后
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmDlgDataExport_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (_SheetCreator != null) _SheetCreator.ClearElement();
            if (_ToolCreator != null) _ToolCreator.Clear();
            if (_AreaCreator != null) _AreaCreator.Clear();
            regionTree.ClearNodeCheck(regionTree.Nodes);
            regionTree.Clear();
            FrameworkHelper.AxMapControl.CurrentTool = null;
            IActiveView pAV = (m_Application.Document as IMxDocument).ActiveView;

            IGraphicsContainer pGeoContainer = pAV as IGraphicsContainer;

            if (m_pElementUserDraw != null)
                try
                {
                    pGeoContainer.DeleteElement(m_pElementUserDraw);
                    //IActiveView pAV = ((AxMapControl)statusController.Host).ActiveView;
                    pAV.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, pAV.Extent);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

            dlgDataExportForm = null;
        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExport_Click(object sender, EventArgs e)
        {
            #region 定义变量
            List<IFeatureClass> pFeatClsesTarget = new List<IFeatureClass>();
            List<IFeatureClass> pFeatClses = new List<IFeatureClass>();
            List<string> targetFeatCLsNames = new List<string>();
            List<string> whereClauses = new List<string>();
            string expPath = txtExportPath.Text;
            ProgressAll = new Progressor() { ProgressBar = progressBarAll };
            ProgressSub = new Progressor() { ProgressBar = progressBarSub };

            //FrmNewLog frmNewLog = new FrmNewLog(OperateType.DataExport);

            dataGridViewByMap.Refresh();
            #endregion

            try
            {
                #region 条件判断
                if (!(m_Application as IFramework).IsMapCtrlactive)
                {
                    MsgHelper.ShowInfomationMsgbox("请先切换到数据视图再进行此操作！");
                    return;
                }

                if (expPath == "")
                {
                    MsgHelper.ShowInfomationMsgbox("请选择导出路径！");
                    return;
                }

                if (!AnyLayerChecked())
                {
                    MsgHelper.ShowInfomationMsgbox("未选择要导出的图层！");
                    return;
                }
                if (swtbtnAll.Value != true)
                {
                    switch(sptbctlGeo.SelectedTab.Text)
                    {
                        case "图幅": //按图幅导出
                            if (_SheetCreator.CheckedSheets == null || _SheetCreator.CheckedSheets.Count == 0)
                            {
                                MsgHelper.ShowInfomationMsgbox("未选择图幅！");
                                return;
                            }
                            break;
                        case "自定义范围": //按自定义范围
                            if (_ToolCreator.Geometry == null)
                            {
                                MsgHelper.ShowInfomationMsgbox("未划定范围！");
                                return;
                            }
                            break;

                        case "测区":
                            if (_AreaCreator.CheckedFeatures == null || _AreaCreator.CheckedFeatures.Count==0)
                            {
                                MsgHelper.ShowInfomationMsgbox("未选择测区！");
                                return;
                            }
                            break;

                        case "行政区":
                            if (regionTree.SelectedGeometry == null)
                            {
                                MsgHelper.ShowInfomationMsgbox("未选择行政区！");
                                return;
                            }
                            break;
                        default:
                            return;
                    }
                }
                #endregion

                #region 初始化参数
                for (int i = 0; i < dataGridViewByMap.Rows.Count; i++)
                {
                    if (Convert.ToBoolean(dataGridViewByMap.Rows[i].Cells[0].Value) == true && dataGridViewByMap.Rows[i].Tag is IFeatureLayer)
                    {
                        IFeatureLayer pFeatLyr = dataGridViewByMap.Rows[i].Tag as IFeatureLayer;

                        pFeatClses.Add(pFeatLyr.FeatureClass);
                        targetFeatCLsNames.Add(StringHelper.ConvertWRTNull(dataGridViewByMap.Rows[i].Cells[2].Value) != "" ?
                            StringHelper.ConvertWRTNull(dataGridViewByMap.Rows[i].Cells[2].Value) : ((dataGridViewByMap.Rows[i].Tag as IFeatureLayer).FeatureClass as IDataset).Name);

                        //ILayerGeneralProperties pLayerGeneralProperties = pFeatLyr as ILayerGeneralProperties;
                        //string lyrDescription = pLayerGeneralProperties.LayerDescription;

                        whereClauses.Add(StringHelper.ConvertWRTNull(dataGridViewByMap.Rows[i].Cells[3].Value));
                    }
                }
                #endregion

                btnCancel.Visible = true;
                breaked = false;

                #region 判断导出数据的类型
                zjgisWorkspaceType workspaceType;
                switch (cboType.SelectedIndex)
                {
                    case 0:
                        workspaceType = zjgisWorkspaceType.gdb;
                        break;

                    case 1:
                        workspaceType = zjgisWorkspaceType.mdb;
                        break;

                    case 2:
                        workspaceType = zjgisWorkspaceType.shp;
                        break;
                    case 3:
                        ExportDwgNew(expPath);
                        return;
                    case 4:
                        ExportE00(expPath);
                        return;
                    //case 5:
                    //    ExportMif();
                    //    return;
                    default:
                        return;
                }
                #endregion

                if (sptbctlGeo.SelectedTab ==sptbitmSheet && chkEpByTufu.Checked)
                {
                    #region 按图幅分幅导出
                    foreach (Mapsheet tuFu in _SheetCreator.CheckedSheets)
                    {
                        if (breaked) break;

                        dlgDataExportConstruct = new DlgDataExportConstruct();
                        dlgDataExportConstruct.FeatClsListSource = pFeatClses;
                        dlgDataExportConstruct.TargetFeatClsNames = targetFeatCLsNames;
                        dlgDataExportConstruct.WhereClauses = whereClauses;
                        dlgDataExportConstruct.Geometry = tuFu.Geometry as IPolygon;
                        dlgDataExportConstruct.NeedCut = chkCut.Checked;
                        dlgDataExportConstruct.IsDelNullData = chkDelNullData.Checked;
                        dlgDataExportConstruct.SetProcessBarMax = setSubPgbMax;
                        dlgDataExportConstruct.SetProcessBarCurrent = setSubPgbCurrent;
                        dlgDataExportConstruct.NeedCut = chkCut.Checked;
                        dlgDataExportConstruct.WorkspaceType = workspaceType;
                        dlgDataExportConstruct.Path = expPath + "\\" + tuFu.Code;

                        dlgDataExportConstruct.CreateWsOnly = chkUseGP.Checked;

                        LogHelper.WriteLog("开始导出图幅[" + tuFu.Code + "]范围内的数据...\n");

                        //doing = true;

                        if (!dlgDataExportConstruct.Operate())
                        {
                            if (breaked)
                            {
                                LogHelper.WriteLog("导出被终止。\n\n");
                                MsgHelper.ShowInfomationMsgbox("导出操作被终止！");
                                //breaked = false;
                            }
                            else
                            {
                                LogHelper.WriteErrLog("构造失败！！！\n\n");
                                MsgHelper.ShowWarningMsgbox("构造失败！详细信息请查看日志。");
                            }
                        }
                        else
                        {
                            List<DlgDataConvert> dlgDataConverts = dlgDataExportConstruct.DlgDataConverts;

                            dlgDataExport = new DlgDataExport();
                            dlgDataExport.Task = dlgDataConverts;
                            dlgDataExport.SetProcessBarMax = setAllPgbMax;
                            dlgDataExport.SetProcessBarCurrent = setAllPgbCurrent;
                            dlgDataExport.NeedRecord = chkAddResult.Checked;

                            if (dlgDataExport.Operate())
                            {
                                LogHelper.WriteLog("图幅[" + tuFu.Code + "]范围内的数据导出成功。\n\n");
                            }
                            else
                            {
                                if (breaked)
                                {
                                    LogHelper.WriteLog("导出被终止。\n\n");
                                }
                                else
                                {
                                    LogHelper.WriteErrLog("图幅[" + tuFu.Code + "]范围内的数据导出操作失败！！！\n\n");
                                }
                            }

                            if (chkAddResult.Checked) pFeatClsesTarget.AddRange(dlgDataExport.FeatClsListTarget);
                        }
                        GC.Collect();
                    }
                    #endregion
                }
                else if (sptbctlGeo.SelectedTab == sptbitmArea && chkEpByCeQu.Checked)
                {
                    #region 按测区分区导出
                    if (spgrdArea.PrimaryGrid.Rows == null || spgrdArea.PrimaryGrid.Rows.Count == 0)
                        return;
                    foreach (GridRow r in spgrdArea.PrimaryGrid.Rows)
                    {
                        if (breaked) break;
                        if ((bool)r.Cells["colCheck"].Value == false) continue;                      
                        dlgDataExportConstruct = new DlgDataExportConstruct();
                        dlgDataExportConstruct.FeatClsListSource = pFeatClses;
                        dlgDataExportConstruct.TargetFeatClsNames = targetFeatCLsNames;
                        dlgDataExportConstruct.WhereClauses = whereClauses;
                        dlgDataExportConstruct.Geometry = ((IFeature)r.Tag).Shape as IPolygon;
                        dlgDataExportConstruct.NeedCut = chkCut.Checked;
                        dlgDataExportConstruct.IsDelNullData = chkDelNullData.Checked;
                        dlgDataExportConstruct.SetProcessBarMax = setSubPgbMax;
                        dlgDataExportConstruct.SetProcessBarCurrent = setSubPgbCurrent;
                        dlgDataExportConstruct.NeedCut = chkCut.Checked;
                        dlgDataExportConstruct.WorkspaceType = workspaceType;
                        dlgDataExportConstruct.Path = expPath + "\\" + r.Cells["colName"].Value.ToString();

                        dlgDataExportConstruct.CreateWsOnly = chkUseGP.Checked;

                        LogHelper.WriteLog("开始导出测区[" + r.Cells["colName"].Value.ToString() + "]范围内的数据...\n");

                        //doing = true;

                        if (!dlgDataExportConstruct.Operate())
                        {
                            if (breaked)
                            {
                                LogHelper.WriteLog("导出被终止。\n\n");
                                MsgHelper.ShowInfomationMsgbox("导出操作被终止！");
                            }
                            else
                            {
                                LogHelper.WriteErrLog("构造失败！！！\n\n");

                                MsgHelper.ShowWarningMsgbox("构造失败！详细信息请查看日志。");
                            }
                        }
                        else
                        {
                            List<DlgDataConvert> dlgDataConverts = dlgDataExportConstruct.DlgDataConverts;

                            dlgDataExport = new DlgDataExport();
                            dlgDataExport.Task = dlgDataConverts;
                            dlgDataExport.SetProcessBarMax = setAllPgbMax;
                            dlgDataExport.SetProcessBarCurrent = setAllPgbCurrent;
                            dlgDataExport.NeedRecord = chkAddResult.Checked;

                            if (dlgDataExport.Operate())
                            {
                                LogHelper.WriteLog("测区[" + r.Cells["colName"].Value.ToString() + "]范围内的数据导出成功。\n\n");
                            }
                            else
                            {
                                if (breaked)
                                {
                                    LogHelper.WriteLog("导出被终止。\n\n");
                                    breaked = false;
                                }
                                else
                                {
                                    LogHelper.WriteErrLog("测区[" + r.Cells["colName"].Value.ToString() + "]范围内的数据导出操作失败！！！\n\n");
                                }
                            }
                            if (chkAddResult.Checked) pFeatClsesTarget.AddRange(dlgDataExport.FeatClsListTarget);
                        }
                        GC.Collect();
                    }
                    #endregion
                }
                else
                {
                    #region 导出到一个文件或者文件夹下
                    dlgDataExportConstruct = new DlgDataExportConstruct();
                    dlgDataExportConstruct.FeatClsListSource = pFeatClses;
                    dlgDataExportConstruct.TargetFeatClsNames = targetFeatCLsNames;
                    dlgDataExportConstruct.WhereClauses = whereClauses;
                    dlgDataExportConstruct.NeedCut = chkCut.Checked;
                    dlgDataExportConstruct.IsDelNullData = chkDelNullData.Checked;
                    dlgDataExportConstruct.SetProcessBarMax = setSubPgbMax;
                    dlgDataExportConstruct.SetProcessBarCurrent = setSubPgbCurrent;
                    dlgDataExportConstruct.WorkspaceType = workspaceType;
                    dlgDataExportConstruct.Path = expPath;

                    dlgDataExportConstruct.CreateWsOnly = chkUseGP.Checked;                    
                    if(swtbtnAll.Value!=true)
                    {
                        switch (sptbctlGeo.SelectedTab.Text)
                        {
                            case "图幅": //按图幅导出
                                dlgDataExportConstruct.Geometry = (IPolygon)_SheetCreator.GetSelectGeometry();
                                break;
                            case "自定义范围": //按自定义范围
                                dlgDataExportConstruct.Geometry = (IPolygon)_ToolCreator.Geometry;
                                break;

                            case "测区":
                                dlgDataExportConstruct.Geometry = (IPolygon)_AreaCreator.GetSelectGeometry();
                                break;

                            case "行政区":
                                dlgDataExportConstruct.Geometry = (IPolygon)regionTree.SelectedGeometry;
                                break;

                            default:
                                return;
                        }
                    }

                    //doing = true;

                    if (!dlgDataExportConstruct.Operate())
                    {
                        if (breaked)
                        {
                            LogHelper.WriteLog("导出被终止。\n\n");
                            breaked = false;
                        }
                        else
                        {
                            LogHelper.WriteErrLog("构造失败！！！\n\n");
                        }
                    }
                    else
                    {
                        List<DlgDataConvert> dlgDataConverts = dlgDataExportConstruct.DlgDataConverts;

                        dlgDataExport = new DlgDataExport();
                        dlgDataExport.Task = dlgDataConverts;
                        dlgDataExport.SetProcessBarMax = setAllPgbMax;
                        dlgDataExport.SetProcessBarCurrent = setAllPgbCurrent;

                        dlgDataExport.NeedRecord = chkAddResult.Checked;

                        if (dlgDataExport.Operate())
                        {
                            LogHelper.WriteLog("导出成功。\n");
                        }
                        else
                        {
                            if (breaked)
                            {
                                LogHelper.WriteLog("导出被终止。\n\n");
                                breaked = false;
                            }
                            else
                            {
                                LogHelper.WriteErrLog("导出失败！！！\n\n");
                            }
                        }

                        if (chkAddResult.Checked) pFeatClsesTarget.AddRange(dlgDataExport.FeatClsListTarget);
                    }
                    #endregion
                }

                #region 加载导出结果
                if (chkAddResult.Checked)
                {
                    LogHelper.WriteLog("正在加载导出结果...");
                    foreach (IFeatureClass pFeatCLs in pFeatClsesTarget)
                    {
                        IFeatureLayer pFeatLyr = pFeatCLs.GetFeatureLayer();
                        pFeatLyr.Name = pFeatCLs.AliasName + "_导出";
                        m_pMap.AddLayer(pFeatLyr);
                    }
                    LogHelper.WriteLog("加载完毕。");                   
                }
                #endregion

                //if (!chkLog.Checked) 
                MsgHelper.ShowInfomationMsgbox("导出完毕！");

                (m_Application as IFramework).DockManager.ActivateDockPanel("日志");
            }

            catch (Exception ex)
            {
                MsgHelper.ShowWarningMsgbox("导出失败！" + ex.Message);
                LogHelper.WriteErrLog("导出失败！" + ex.Message);
            }
            finally
            {
                #region 扫尾工作
                dlgDataExportConstruct = null;
                dlgDataExport = null;
                ProgressAll.Stop();
                ProgressSub.Stop();
                //doing = false;
                breaked = true;
                pFeatClses = null;
                targetFeatCLsNames = null;
                whereClauses = null;
                btnCancel.Visible = false;
                #endregion
            }
        }
        /// <summary>
        /// 选择导出路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            switch (cboType.SelectedIndex)
            {
                case 0://gdb
                case 1://mdb  
                case 3://dwg
                    {
                        if ((sptbctlGeo.SelectedTab == sptbitmSheet && chkEpByTufu.Checked) ||
                            (sptbctlGeo.SelectedTab == sptbitmArea && chkEpByCeQu.Checked))
                        {
                            FolderBrowserDialog fbdlg = new FolderBrowserDialog();
                            fbdlg.ShowNewFolderButton = true;
                            fbdlg.Description = "选择导出路径";
                            if (fbdlg.ShowDialog() == DialogResult.OK)
                            {
                                txtExportPath.Text = fbdlg.SelectedPath;
                            }
                        }
                        else
                        {
                            saveFileExport.Title = "指定目标文件";
                            if (cboType.SelectedIndex == 0)
                            {
                                saveFileExport.Filter = "File Geodatabase (*.gdb)| *.gdb";
                                if (saveFileExport.ShowDialog() == DialogResult.OK)
                                {
                                    txtExportPath.Text = saveFileExport.FileName.Substring(0, saveFileExport.FileName.Length - 4);
                                }
                            }
                            else if (cboType.SelectedIndex == 1)
                            {
                                saveFileExport.Filter = "Personal Geodatabase(*.mdb) | *.mdb";
                                if (saveFileExport.ShowDialog() == DialogResult.OK)
                                {
                                    txtExportPath.Text = saveFileExport.FileName.Substring(0, saveFileExport.FileName.Length - 4);
                                }
                            }
                            else if (cboType.SelectedIndex == 3)
                            {
                                saveFileExport.Filter = "AutoCAD dwg 文件(*.dwg) | *.dwg";
                                if (saveFileExport.ShowDialog() == DialogResult.OK)
                                {
                                    txtExportPath.Text = saveFileExport.FileName;
                                }
                            }
                        }
                        break;
                    }
                case 2://shp
                case 4://e00
                    //case 5://mif
                    {
                        FolderBrowserDialog fbdlg = new FolderBrowserDialog();
                        fbdlg.ShowNewFolderButton = true;
                        fbdlg.Description = "选择导出路径";
                        if (fbdlg.ShowDialog() == DialogResult.OK)
                        {
                            txtExportPath.Text = fbdlg.SelectedPath;
                            //m_pExportType = cboType.SelectedIndex;
                        }
                        break;
                    }
                default:
                    {
                        break;
                    }
            }
            txtExportPath.Tooltip = txtExportPath.Text;
        }
        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        /// <summary>
        /// 保存规则
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveRule_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridViewByMap.RowCount == 0) return;

                #region 判断是否有选中图层
                List<DataGridViewRow> dgrRows = new List<DataGridViewRow>();
                for (int i = 0; i < dataGridViewByMap.Rows.Count; i++)
                {
                    if (Convert.ToBoolean(dataGridViewByMap.Rows[i].Cells[0].Value) == true && dataGridViewByMap.Rows[i].Tag is IFeatureLayer)
                    {
                        dgrRows.Add(dataGridViewByMap.Rows[i]);
                    }
                }

                if (dgrRows.Count == 0)
                {
                    MsgHelper.ShowInfomationMsgbox("没有图层被选中，无需保存。");
                    return;
                }
                #endregion

                #region 设置新方案名称，或者选择已有方案
                FrmSaveRule frmSaveRule = new FrmSaveRule(zjgisRuleType.dlgExp);
                frmSaveRule.RuleName = ruleName;

                if (frmSaveRule.ShowDialog() == DialogResult.Cancel) return;

                object obj = frmSaveRule.Rule;
                DataExportRule dataExportRule;

                bool isNewRule = false;

                if (obj is string)
                {
                    dataExportRule = new DataExportRule();
                    dataExportRule.RuleName = obj.ToString();
                    isNewRule = true;
                }
                else if (obj is DataExportRule)
                {
                    dataExportRule = obj as DataExportRule;
                }
                else
                {
                    MsgHelper.ShowWarningMsgbox("选择方案名称无效，无法保存！");
                    return;
                }
                #endregion

                #region 是否裁切、导出类型
                dataExportRule.Cutable = chkCut.Checked;
                dataExportRule.IsDelNullData = chkDelNullData.Checked;
                dataExportRule.ExportType = cboType.SelectedItem.ToString();
                #endregion

                #region 导出图层
                List<DataExportLayer> dataExportLayers = new List<DataExportLayer>();
                foreach (DataGridViewRow dgvRow in dgrRows)
                {
                    DataExportLayer dataExportLayer = new DataExportLayer();

                    IFeatureLayer pFeatureLayer = dgvRow.Tag as IFeatureLayer;

                    dataExportLayer.FeatLyrName = pFeatureLayer.Name;
                    dataExportLayer.SourceFeatClsName = (pFeatureLayer.FeatureClass as IDataset).Name;

                    string targetFeatClsName = StringHelper.ConvertWRTNull(dgvRow.Cells[2].Value);
                    if (targetFeatClsName == "") targetFeatClsName = (pFeatureLayer.FeatureClass as IDataset).Name;
                    dataExportLayer.TargetFeatClsName = targetFeatClsName;

                    dataExportLayer.SQL = StringHelper.ConvertWRTNull(dgvRow.Cells[3].Value);
                    dataExportLayers.Add(dataExportLayer);
                }
                dataExportRule.DataExportLayers = dataExportLayers;
                #endregion

                #region 设置空间范围
                SpatialSetting spatialSetting = new SpatialSetting();

                if (swtbtnAll.Value == true)
                {
                    spatialSetting.SpatialType = 0;
                }
                else
                {
                    switch (sptbctlGeo.SelectedTab.Text)
                    {
                        case "图幅":
                            spatialSetting.SpatialType = 1;

                            MapsheetInfo mapsheetInfo = new MapsheetInfo();
                            mapsheetInfo.Splitable = chkEpByTufu.Checked;
                            mapsheetInfo.Scale = cmbScale.Text;

                            string mapNo = "";
                            foreach (Mapsheet tufu in _SheetCreator.CheckedSheets)
                            {
                                mapNo = mapNo + tufu.Code + ";";
                            }

                            if (mapNo != "") mapNo = mapNo.Substring(0, mapNo.Length - 1);
                            mapsheetInfo.MapNo = mapNo;

                            spatialSetting.MapsheetInfo = mapsheetInfo;

                            break;

                        case "测区":
                            spatialSetting.SpatialType = 2;
                            //CequInfo cequInfos = new CequInfo();

                            //List<Cequ> cequs = new List<Cequ>();
                            //if(_AreaCreator.CheckedFeatures==null||_AreaCreator.CheckedFeatures.Count==0) return;
                            //foreach (IFeature fc in _AreaCreator.CheckedFeatures)
                            //{
                            //    if (fc.Shape.IsEmpty == true) continue;

                            //    IXMLWriter pWriter = new XMLWriterClass();
                            //    IXMLStream pStream = new XMLStreamClass();

                            //    pWriter.WriteTo(pStream as IStream);

                            //    IXMLSerializer pSerializer = new XMLSerializerClass();
                            //    pSerializer.WriteObject(pWriter, null, null, "Shape", "", fc.Shape);
                            //    string shape = pStream.SaveToString();

                            //    Cequ cq = new Cequ();
                            //    cq.Geometry = shape;
                            //    cq.Name =fc.get_Value(fc.Fields.FindField( _AreaCreator.m_nameField)).ToString();

                            //    cequs.Add(cq);
                            //}
                            //cequInfos.Cequs = cequs;
                            //spatialSetting.CequInfo = cequInfos;
                            break;

                        case "自定义范围":
                            spatialSetting.SpatialType = 2;

                            //CequInfo cequInfo = new CequInfo();

                            //IGeometry pGeometry = _ToolCreator.Geometry;

                            //if (pGeometry != null && pGeometry.IsEmpty == false)
                            //{

                            //    IXMLWriter pWriter = new XMLWriterClass();
                            //    IXMLStream pStream = new XMLStreamClass();

                            //    pWriter.WriteTo(pStream as IStream);

                            //    IXMLSerializer pSerializer = new XMLSerializerClass();
                            //    pSerializer.WriteObject(pWriter, null, null, "Shape", "", pGeometry);
                            //    string shape = pStream.SaveToString();

                            //    cequInfo.Geometry = shape;
                            //}

                            //spatialSetting.CequInfo = cequInfo;

                            break;

                        case "行政区":
                            spatialSetting.SpatialType = 3;

                            XzqInfo xzqInfo = new XzqInfo();

                            List<Xzq> mXzqChecked = new List<Xzq>();
                            List<Xzq> xzqs = GetXZQ(regionTree.Nodes, mXzqChecked);
                            xzqInfo.Xzqs = xzqs;
                            spatialSetting.XzqInfo = xzqInfo;

                            break;
                        default:
                            MsgHelper.ShowWarningMsgbox("空间范围设置异常！");
                            return;
                    }
                }

                dataExportRule.SpatialSetting = spatialSetting;
                #endregion

                #region 保存方案
                if (isNewRule)
                {
                    List<DataExportRule> dataExportRules = ConvertHelper.DataConvert.DataExportRules;
                    dataExportRules.Add(dataExportRule);
                }
                ConfigHelper.SaveObject<DataConvert>(ConvertHelper.DataConvert, "Rule");
                #endregion

                ruleName = dataExportRule.RuleName;

                MsgHelper.ShowInfomationMsgbox("保存成功。");
            }
            catch (Exception ex)
            {
                MsgHelper.ShowWarningMsgbox("保存失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 获取树中选择的行政区
        /// </summary>
        /// <param name="tnc"></param>
        /// <returns></returns>
        private List<Xzq> GetXZQ(NodeCollection tnc, List<Xzq> xzqChecked)
        {
            foreach (Node node in tnc)
            {
                if (node.CheckState == CheckState.Checked)
                {
                    Xzq xzq = new Xzq();
                    xzq.Code = node.Name;
                    xzq.Name = node.Text;
                    xzqChecked.Add(xzq);
                }
                else if (node.CheckState == CheckState.Indeterminate)
                {
                    GetXZQ(node.Nodes, xzqChecked);
                }
            }
            return xzqChecked;
        }


        /// <summary>
        /// 打开规则
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenRule_Click(object sender, EventArgs e)
        {
            try
            {
                FrmSelRule frmSelectRule = new FrmSelRule(zjgisRuleType.dlgExp);

                frmSelectRule.TypeComboxVisable = true;
                if (frmSelectRule.ShowDialog() != DialogResult.OK) return;

                DataExportRule dataExportRule = frmSelectRule.Rule as DataExportRule;
                if (dataExportRule == null) return;

                Cursor = Cursors.WaitCursor;

                ruleName = dataExportRule.RuleName;

                #region 图层信息
                List<DataExportLayer> dataExportLayers = dataExportRule.DataExportLayers;
                foreach (DataGridViewRow dgvR in this.dataGridViewByMap.Rows)
                {
                    if (dgvR.Tag == null || !(dgvR.Tag is IFeatureLayer)) continue;

                    IFeatureLayer pFeatLyr = dgvR.Tag as IFeatureLayer;
                    List<DataExportLayer> dels;
                    DataExportLayer dataExportLayer = null;
                    string lyrName = pFeatLyr.Name;
                    string dsName = (pFeatLyr.FeatureClass as IDataset).Name;

                    switch (frmSelectRule.MatchType)
                    {
                        case 0:

                            dels = ListHelper.GetEnumeratorItems(dataExportLayers, "FeatLyrName", lyrName);

                            if (dels.Count == 1)
                            {
                                dataExportLayer = dels[0];
                            }
                            else if (dels.Count > 1)
                            {
                                dataExportLayer = ListHelper.GetEnumeratorItem(dels, "SourceFeatClsName", dsName);
                                if (dataExportLayer == null) dataExportLayer = dels[0];
                            }

                            break;

                        case 1:

                            dels = ListHelper.GetEnumeratorItems(dataExportLayers, "SourceFeatClsName", dsName);

                            if (dels.Count == 1)
                            {
                                dataExportLayer = dels[0];
                            }
                            else if (dels.Count > 1)
                            {
                                dataExportLayer = ListHelper.GetEnumeratorItem(dels, "FeatLyrName", lyrName);
                                if (dataExportLayer == null) dataExportLayer = dels[0];
                            }

                            break;
                    }

                    if (dataExportLayer != null)
                    {
                        dgvR.Cells[0].Value = true;
                        dgvR.Cells[2].Value = StringHelper.ConvertWRTNull(dataExportLayer.TargetFeatClsName);
                        dgvR.Cells[3].Value = StringHelper.ConvertWRTNull(dataExportLayer.SQL);
                    }
                    else
                    {
                        dgvR.Cells[0].Value = false;
                    }
                }
                #endregion

                #region 裁切、导出类型
                chkCut.Checked = dataExportRule.Cutable;
                chkDelNullData.Checked = dataExportRule.IsDelNullData;
                cboType.Text = dataExportRule.ExportType.ToLower();
                #endregion

                #region 空间范围信息
                SpatialSetting spatialSetting = dataExportRule.SpatialSetting;
                swtbtnAll.Value = false;
                switch (spatialSetting.SpatialType)
                {
                    case 0:
                        swtbtnAll.Value = true;
                        break;

                    case 1:
                        sptbctlGeo.SelectedTab = sptbitmSheet;
                        MapsheetInfo mapsheetInfo = spatialSetting.MapsheetInfo;
                        if (mapsheetInfo == null) break;

                        int scale = int.Parse(mapsheetInfo.Scale);
                        cmbScale.Text = scale.ToString();
                        chkEpByTufu.Checked = mapsheetInfo.Splitable;

                        string[] tufuStrs = mapsheetInfo.MapNo.Split(';');
                        List<string> tufuList = new List<string>(tufuStrs);
                        _SheetCreator.SelectByCodes(tufuList);
                        break;

                    case 2:
                        sptbctlGeo.SelectedTab = sptbitmPoly;
                        //else
                        //{
                        //    sptbctlGeo.SelectedTabIndex = 4;
                            //CequInfo cequInfo = spatialSetting.CequInfo;
                            //if (cequInfo == null) break;
                            //try
                            //{
                            //    IXMLReader pReader = new XMLReaderClass();
                            //    IXMLStream pStream = new XMLStreamClass();

                            //    string xml = cequInfo.Geometry;
                            //    xml = xml.Replace("&lt;", "<");
                            //    xml = xml.Replace("&gt;", ">");
                            //    pStream.LoadFromString(xml);
                            //    pReader.ReadFrom(pStream as IStream);

                            //    IXMLSerializer pSerializer = new XMLSerializerClass();

                            //    IGeometry pGeometry = pSerializer.ReadObject(pReader, null, null) as IGeometry;
                            //    if (pGeometry == null || pGeometry.IsEmpty) break;

                            //    (m_pMap as IActiveView).Extent = pGeometry.Envelope;
                            //    (m_pMap as IActiveView).Refresh();

                            //    //chooseFWX2.AfterButtonOkEvent(pGeometry, 0);
                            //    //AfterButtonOkEvent(pGeometry, 0); 
                            //}

                            //catch (Exception ex)
                            //{
                            //    MsgHelper.ShowWarningMsgbox("反序列化测区图形失败：" + ex.Message);
                            //}
                        //}                      
                        break;

                    case 3:
                        sptbctlGeo.SelectedTab =sptbitmRegion;
                        XzqInfo xzqInfo = spatialSetting.XzqInfo;
                        if (xzqInfo == null) break;
                        List<XZQ> xzqs = new List<XZQ>();
                        List<string> codes = new List<string>();
                        foreach (Xzq xzq in xzqInfo.Xzqs)
                        {
                            codes.Add(xzq.Code);
                        }
                        regionTree.SelectByCodes(codes);
                        break;
                }
                #endregion

                MsgHelper.ShowInfomationMsgbox("加载方案成功。");
            }
            catch (Exception ex)
            {
                MsgHelper.ShowWarningMsgbox("加载方案失败：" + ex.Message);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        #region 进度条事件
        /// <summary>
        /// 
        /// </summary>
        /// <param name="max"></param>
        private void setSubPgbMax(int max)
        {
            ProgressSub.SetMaxValue(max);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="current"></param>
        private void setSubPgbCurrent(int current)
        {
            ProgressSub.SetCurrentValue(current);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="max"></param>
        private void setAllPgbMax(int max)
        {
            ProgressAll.SetMaxValue(max);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="current"></param>
        private void setAllPgbCurrent(int current)
        {
            ProgressAll.SetCurrentValue(current);
        }
        #endregion

        #region 右键菜单
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void pItemUnSelectAll_Click(object sender, EventArgs e)
        {
            for (int i = dataGridViewByMap.Rows.Count - 1; i >= 0; i--)
            {
                dataGridViewByMap.Rows[i].Cells[0].Value = false;
            }

            dataGridViewByMap.RefreshEdit();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void pItemSelectAll_Click(object sender, EventArgs e)
        {
            for (int i = dataGridViewByMap.Rows.Count - 1; i >= 0; i--)
            {
                dataGridViewByMap.Rows[i].Cells[0].Value = true;
            }

            dataGridViewByMap.RefreshEdit();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void pItemCheckSelectAll_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow pRow in dataGridViewByMap.SelectedRows)
            {
                pRow.Cells[0].Value = true;
            }

            dataGridViewByMap.RefreshEdit();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void pItemUnCheckSelectAll_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow pRow in dataGridViewByMap.SelectedRows)
            {
                pRow.Cells[0].Value = false;
            }

            dataGridViewByMap.RefreshEdit();
        }
        #endregion

        #endregion

        /// <summary>
        /// 加载数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddData_Click(object sender, EventArgs e)
        {
            List<IDataset> pSelDatasets = frmAddData.GetSelectDatasets();
            if (pSelDatasets.Count > 0)
            {
                if (pSelDatasets[0].Type == esriDatasetType.esriDTFeatureClass)
                {
                    IFeatureClass pFeatCls = pSelDatasets[0] as IFeatureClass;
                    if (pFeatCls.ShapeType == esriGeometryType.esriGeometryPolygon && pFeatCls.FeatureType == esriFeatureType.esriFTSimple)
                    {
                        IField lv_field;
                        cmbFields.Items.Clear();
                        for (int i = 0; i < pFeatCls.Fields.FieldCount; i++)
                        {
                            lv_field = pFeatCls.Fields.get_Field(i);
                            if (lv_field.Type != esriFieldType.esriFieldTypeGeometry && lv_field.Name != "SHAPE_Area" && lv_field.Name != "SHAPE_Length")
                            {
                                cmbFields.Items.Add(lv_field.Name);
                                if (lv_field.Name.ToUpper() == "NAME")
                                    _AreaCreator.m_nameField = lv_field.Name;
                                else
                                {
                                    if (_AreaCreator.m_nameField != "NAME" && lv_field.Name.ToUpper().Contains("NAME"))
                                        _AreaCreator.m_nameField = lv_field.Name;
                                }
                            }
                        }
                        cmbFields.Text = _AreaCreator.m_nameField;
                        _AreaCreator.AddArea(pFeatCls);
                    }
                    else
                    {
                        MsgHelper.ShowInfomationMsgbox("您必须选择多边形要素类！");
                        return;
                    }
                }
                else
                {
                    MsgHelper.ShowInfomationMsgbox("您选择的不是矢量要素类，请重新选择！");
                    return;
                }
            }
            else
            {
                MsgHelper.ShowInfomationMsgbox("您没有选中的要素类，或选中要素类已破坏，请检查!");
            }
            frmAddData.Hide();
        }

        /// <summary>
        /// 画用户权限内的范围
        /// </summary>
        /// <param name="pPolyUserDraw"></param>
        private void GeometryUserDraw(IPolygon pPolyUserDraw)
        {
            if (pPolyUserDraw == null || pPolyUserDraw.IsEmpty) return; ;
            IPolyline pPolyline = pPolyUserDraw.ToPolyline();

            IRgbColor pRgbColor = new RgbColorClass();
            pRgbColor.Red = 255;
            pRgbColor.Green = 155;
            pRgbColor.Blue = 0;

            IActiveView pActiveView = (m_Application.Document as IMxDocument).ActiveView;
            IGraphicsContainer pGeoContainer = pActiveView as IGraphicsContainer;
            if (m_pElementUserDraw != null)
                try
                {
                    pGeoContainer.DeleteElement(m_pElementUserDraw);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

            ISimpleLineSymbol pLineSymbol = new SimpleLineSymbolClass();
            ILineElement pLineElement = new LineElementClass();
            pLineSymbol.Style = esriSimpleLineStyle.esriSLSSolid;
            pLineSymbol.Color = pRgbColor;
            pLineSymbol.Width = 3;
            pLineElement.Symbol = pLineSymbol;
            m_pElementUserDraw = pLineElement as IElement;
            m_pElementUserDraw.Geometry = pPolyline;
            pGeoContainer.AddElement(m_pElementUserDraw, 0);
            pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, pActiveView.Extent);
        }

        /// <summary>
        /// 初始化图层列表和图层树
        /// </summary>
        private void RefreshCurMapLayer()
        {
            //当前地图的图层
            if (m_Application != null && (m_Application.Document as IMxDocument).ActiveView.FocusMap != null)
            {

                m_pMap = (m_Application.Document as IMxDocument).ActiveView.FocusMap;
            }
            else
                return;

            dataGridViewByMap.Rows.Clear();
            dataGridViewByMap.Columns[1].ReadOnly = true;

            #region 界面上仅显示图层名，没有组的信息
            //读取所有图层
            //if (m_pMap != null)
            //{
            //    List<IFeatureLayer> pFeaturelyrs = MapHelper.GetAllLayer<IFeatureLayer>(m_pMap);
            //    IFeatureLayer pFeaturelayer;
            //    string strFclsName = "";
            //    for (int i = 0; i < pFeaturelyrs.Count; i++)
            //    {
            //        pFeaturelayer = pFeaturelyrs[i];
            //        if (!(pFeaturelayer.Valid) || !(pFeaturelayer.Visible)) continue;
            //        if (pFeaturelayer.FeatureClass.FeatureType == esriFeatureType.esriFTSimple || 
            //            pFeaturelayer.FeatureClass.FeatureType == esriFeatureType.esriFTAnnotation )
            //        {
            //            strFclsName = ((IDataset)pFeaturelayer.FeatureClass).Name;
            //            if (strFclsName.IndexOf(".") > 0)
            //            {
            //                strFclsName = strFclsName.Substring(strFclsName.IndexOf(".") + 1);
            //            }
            //            dataGridViewByMap.Rows.Add(1);
            //            dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Cells[0].Value = true;
            //            //数据源显示图层(FeatureLayer)的名称，与TOC对应
            //            dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Cells[1].Value = pFeaturelayer.Name;// strFclsName;

            //            //dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Cells[1].Tag =
            //            //    pFeaturelayer.FeatureClass;
            //            dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Cells[2].Value = strFclsName;

            //            //属性过滤条件默认显示该图层的DefinitionExpression
            //            IFeatureLayerDefinition pFeatureLayerDefinition = pFeaturelayer as IFeatureLayerDefinition;
            //            string definitionExpression = pFeatureLayerDefinition.DefinitionExpression;
            //            dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Cells[3].Value = definitionExpression;

            //            //dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Tag = pFeaturelayer.FeatureClass;
            //            dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Tag = pFeaturelayer;

            //        }
            //    }
            //}
            #endregion

            //读取所有图层
            if (m_pMap != null)
            {
                //TreeView treeView = new TreeView();
                TreeNode root = TocHelper.ConstructLyrTree(m_pMap);
                //treeView.Nodes.Add(root);

                root.Text = "所有图层";
                root.Checked = true;
                root.Expand();
                TreeHelper.CheckChildrenBySelf(root, root.Checked);
                treeView1.Nodes.Add(root);

                List<TreeNode> treeNodes = TreeHelper.GetAllYzTreeNode2(root);

                foreach (TreeNode treeNode in treeNodes)
                {
                    if (treeNode.Tag == null || !(treeNode.Tag is IFeatureLayer)) continue;
                    IFeatureLayer pFeaturelayer;
                    string strFclsName = "";
                    pFeaturelayer = treeNode.Tag as IFeatureLayer;
                    if (!pFeaturelayer.Valid) continue;
                    if (pFeaturelayer.FeatureClass.FeatureType == esriFeatureType.esriFTSimple ||
                        pFeaturelayer.FeatureClass.FeatureType == esriFeatureType.esriFTAnnotation)
                    {
                        strFclsName = ((IDataset)pFeaturelayer.FeatureClass).Name;
                        if (strFclsName.IndexOf(".") > 0)
                        {
                            strFclsName = strFclsName.Substring(strFclsName.IndexOf(".") + 1);
                        }
                        dataGridViewByMap.Rows.Add(1);
                        dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Cells[0].Value = true;

                        //数据源显示图层(FeatureLayer)的名称，与TOC对应(附上组信息)
                        string fullPath = treeNode.FullPath;
                        fullPath = fullPath.Substring(fullPath.IndexOf("\\") + 1);
                        dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Cells[1].Value = fullPath;

                        dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Cells[2].Value = strFclsName;

                        //属性过滤条件默认显示该图层的DefinitionExpression
                        IFeatureLayerDefinition pFeatureLayerDefinition = pFeaturelayer as IFeatureLayerDefinition;
                        string definitionExpression = pFeatureLayerDefinition.DefinitionExpression;
                        dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Cells[3].Value = definitionExpression;

                        //dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Tag = pFeaturelayer.FeatureClass;
                        dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Tag = pFeaturelayer;
                    }

                }
            }
        }

        /// <summary>
        /// 判断是否有图层选中
        /// </summary>
        /// <returns></returns>
        private bool AnyLayerChecked()
        {
            if (dataGridViewByMap.RowCount == 0) return false;
            for (int i = 0; i < dataGridViewByMap.Rows.Count; i++)
            {
                if (Convert.ToBoolean(dataGridViewByMap.Rows[i].Cells[0].Value))
                    return true;
            }
            return false;
        }

        /// <summary>
        /// 保存数据操作日志到Excel
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="workBook"></param>
        private static void SaveAs(string FileName, ComObject workBook)
        {
            int pXlFileFormat = -4143;
            string kong1 = "";
            string kong2 = "";
            bool False1 = false;
            bool False2 = false;
            int pXlSaveAsAccessMode = 1;
            int pXlSaveConflictResolution = 2;
            bool False3 = false;
            object null1 = null;
            object null2 = null;
            bool False4 = false;

            object[] objArr = new object[12];
            objArr[0] = FileName;
            objArr[1] = pXlFileFormat;
            objArr[2] = kong1;
            objArr[3] = kong2;
            objArr[4] = False1;
            objArr[5] = False2;
            objArr[6] = pXlSaveAsAccessMode;
            objArr[7] = pXlSaveConflictResolution;
            objArr[8] = False3;
            objArr[9] = null1;
            objArr[10] = null2;
            objArr[11] = False4;

            workBook.InvokeMethod("SaveAs", objArr);
        }

        /// <summary>
        /// 获取所有选中图层
        /// </summary>
        /// <returns></returns>
        private List<IFeatureLayer> GetCheckLayers()
        {
            List<IFeatureLayer> pLayers = new List<IFeatureLayer>();
            for (int i = 0; i < dataGridViewByMap.Rows.Count; i++)
            {
                if (Convert.ToBoolean(dataGridViewByMap.Rows[i].Cells[0].Value) == true && dataGridViewByMap.Rows[i].Tag is IFeatureLayer)
                {
                    pLayers.Add(dataGridViewByMap.Rows[i].Tag as IFeatureLayer);
                }
            }
            return pLayers;
        }

        #region 导出其它格式数据

        private void ExportE00(string OutPath)
        {
            try
            {
                progressBarSub.Visible = true;
                progressBarAll.Visible = true;

                this.Cursor = Cursors.WaitCursor;
                IGeometry pGeometry = null;
                IFeatureLayer pFeatureLayer = null;
                string strFilter, strTargetFileName;

                if (swtbtnAll.Value != true)
                {
                    if (sptbctlGeo.SelectedTab == sptbitmSheet)
                    {
                        if (_SheetCreator.CheckedSheets.Count == 0)
                        {
                            MsgHelper.ShowInfomationMsgbox("未选择图幅进行导出！");
                            return;
                        }
                        
                        if (chkEpByTufu.Checked == false)  //按合并图幅导出
                        {
                            pGeometry = _SheetCreator.GetSelectGeometry();
                        }
                    }
                    else if (sptbctlGeo.SelectedTab == sptbitmPoly)  //自定义范围导出
                    {
                        if (_ToolCreator.Geometry == null)
                        {
                            MsgHelper.ShowInfomationMsgbox("未定义范围进行导出！");
                            return;
                        }
                        LogHelper.WriteLog("开始导出自定义范围内的选择的图层数据");
                        pGeometry = _ToolCreator.Geometry;
                    }
                    else if (sptbctlGeo.SelectedTab == sptbitmArea)   
                    {
                        if (_AreaCreator.CheckedFeatures.Count == 0)
                        {
                            MsgHelper.ShowInfomationMsgbox("未选择测区范围进行导出！");
                            return;
                        }
                        if (chkEpByCeQu.Checked == false)   //按合并测区导出
                        {
                            LogHelper.WriteLog("开始导出选择的测区范围内的图层数据");
                            pGeometry = _AreaCreator.GetSelectGeometry();
                        }
                    }
                    else if (sptbctlGeo.SelectedTab == sptbitmRegion)    //行政区范围导出
                    {
                        if (regionTree.SelectedGeometry == null)
                        {
                            MsgHelper.ShowInfomationMsgbox("未选择行政区范围进行导出！");
                            return;
                        }
                        LogHelper.WriteLog("开始导出选择的行政区范围内的选择的图层数据");
                        pGeometry = regionTree.SelectedGeometry;
                    }
                }
                else    //全图导出
                {
                    LogHelper.WriteLog("开始导出全图范围内的选择的图层数据");
                }

                E00DwgExport pE00Ep = new E00DwgExport();
                pE00Ep.Path = OutPath;
                pE00Ep.Clip = chkCut.Checked;
                pE00Ep.TempFeatureWorkspace = PlanningGIS.ArcGIS.WorkspaceHelper.CreateOrOpenWorksapce(AppConfig.StartupPath+"\\E00Temp.gdb") as IFeatureWorkspace;
                //pE00Ep.TempFeatureWorkspace = CreateGdbWks(System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location), "E00Temp.gdb");
                for (int i = 0; i < dataGridViewByMap.Rows.Count; i++)
                {
                    if (Convert.ToBoolean(dataGridViewByMap.Rows[i].Cells[0].Value) == true && dataGridViewByMap.Rows[i].Tag is IFeatureLayer)
                    {
                        pFeatureLayer = dataGridViewByMap.Rows[i].Tag as IFeatureLayer;
                        IFeatureClass pFeatCls;
                        pFeatCls = pFeatureLayer.FeatureClass;

                        if (pFeatCls.FeatureType == esriFeatureType.esriFTAnnotation)
                        {
                            LogHelper.WriteLog("暂不支持将注记层导出为E00格式,图层" + pFeatureLayer.Name + "将不被导出");
                            continue;
                        }
                        LogHelper.WriteLog("正在导出图层'" + pFeatureLayer.Name + "'");
                        pE00Ep.FeatureLayer = pFeatureLayer;
                        strTargetFileName = dataGridViewByMap.Rows[i].Cells[2].Value == null ? pFeatureLayer.Name : dataGridViewByMap.Rows[i].Cells[2].Value.ToString();
                        strFilter = dataGridViewByMap.Rows[i].Cells[3].Value == null ? "" : dataGridViewByMap.Rows[i].Cells[3].Value.ToString();
                        if (sptbctlGeo.SelectedTab == sptbitmSheet && chkEpByTufu.Checked && _SheetCreator.CheckedSheets.Count > 0)
                        {
                            DirectoryInfo dir = new DirectoryInfo(OutPath);
                            for (int j = 0; j < _SheetCreator.CheckedSheets.Count; j++)
                            {
                                dir.CreateSubdirectory(_SheetCreator.CheckedSheets[j].Code);
                                pE00Ep.Path = OutPath + "\\" + _SheetCreator.CheckedSheets[j].Code;
                                pE00Ep.FilterGeometry = _SheetCreator.CheckedSheets[j].Geometry;
                                pE00Ep.Filter = strFilter;
                                pE00Ep.TargetFileName = strTargetFileName;
                                //doing = true;
                                LogHelper.WriteLog("开始导出图幅[" + _SheetCreator.CheckedSheets[j].Code + "]范围内的数据...\n");
                                pE00Ep.ExportE00();
                            }
                        }
                        else if (sptbctlGeo.SelectedTab == sptbitmArea && chkEpByCeQu.Checked && _AreaCreator.CheckedFeatures.Count > 0)
                        {
                            DirectoryInfo dir = new DirectoryInfo(OutPath);
                            foreach (GridRow r in spgrdArea.PrimaryGrid.Rows)
                            {
                                if ((bool)r.Cells["colCheck"].Value == false) continue;
                                dir.CreateSubdirectory(r.Cells["colName"].Value.ToString());
                                pE00Ep.Path = OutPath + "\\" + r.Cells["colName"].Value.ToString();
                                pE00Ep.FilterGeometry = ((IFeature)r.Tag).Shape as IPolygon;
                                pE00Ep.Filter = strFilter;
                                pE00Ep.TargetFileName = strTargetFileName;
                                //doing = true;
                                LogHelper.WriteLog("开始导出测区[" + r.Cells["colName"].Value.ToString() + "]范围内的数据...\n");
                                pE00Ep.ExportE00();
                            }
                        }
                        else
                        {
                            pE00Ep.FilterGeometry = pGeometry;
                            pE00Ep.Filter = strFilter;
                            pE00Ep.TargetFileName = strTargetFileName;
                            //doing = true;
                            pE00Ep.ExportE00();
                        }
                    }
                }
                LogHelper.WriteLog("导出完毕");
                MsgHelper.ShowInfomationMsgbox("导出完毕！");
            }
            catch (System.Exception ex)
            {
                MsgHelper.ShowErrorMsgbox("导出失败：" + ex.Message);
            }
            finally
            {
                progressBarSub.Visible = false;
                progressBarAll.Visible = false;
                this.Cursor = Cursors.Default;
            }
        }

        //private void ExportMif()
        //{
        //    try
        //    {
        //        progressBarSub.Visible = true;
        //        progressBarAll.Visible = true;
        //        this.Cursor = Cursors.WaitCursor;
        //        IGeometry pGeometry = null;
        //        IFeatureLayer pFeatureLayer = null;
        //        string strFilter, strTargetFileName;
        //        E00DwgExport pE00Ep = new E00DwgExport();


        //        List<IFeatureLayer> pLayers = GetCheckLayers();
        //        if (pLayers.Count == 0)
        //        {
        //            MsgHelper.ShowWarningMsgbox("未选择要导出的图层！");
        //            return;
        //        }
        //        IFeatureClass pFclsClip = null;
        //        if (swtbtnAll.Value == true)
        //        {
        //            pGeometry = null;
        //            pE00Ep.Clip = false;
        //        }
        //        else
        //        {
        //            if (sptbctlGeo.SelectedTab == sptbitmSheet)
        //            {
        //                if (_SheetCreator.CheckedSheets.Count == 0)
        //                {
        //                    MsgHelper.ShowInfomationMsgbox("未选择图幅进行导出！");
        //                    return;
        //                }
        //                if (!chkEpByTufu.Checked)
        //                {
        //                    pGeometry = _SheetCreator.GetSelectGeometry();
        //                }
        //            }
        //            else if (sptbctlGeo.SelectedTab == sptbitmPoly)
        //            {
        //                pGeometry = _ToolCreator.Geometry;
        //            }
        //            //else if (sptbctlGeo.SelectedTab.Text == "按测区范围")
        //            //{
        //            //    if (chooseFWX2.PolygonFWX == null)
        //            //    {
        //            //        MsgHelper.ShowInfomationMsgbox("未选择测区范围进行导出！");
        //            //        return;
        //            //    }
        //            //    pGeometry = chooseFWX2.PolygonFWX;
        //            //}
        //            else if (sptbctlGeo.SelectedTab == sptbitmRegion)
        //            {
        //                pGeometry = regionTree.SelectedGeometry;
        //                if (pGeometry == null)
        //                {
        //                    MsgHelper.ShowInfomationMsgbox("未选择行政区范围进行导出！");
        //                    return;
        //                }
        //            }
        //        }
        //        ESRI.ArcGIS.Geoprocessor.Geoprocessor GP = null;
        //        ESRI.ArcGIS.DataInteroperabilityTools.QuickExport pQuickEpTool = null;
        //        pQuickEpTool = new ESRI.ArcGIS.DataInteroperabilityTools.QuickExport();
        //        pE00Ep.Path = txtExportPath.Text;
        //        pE00Ep.Clip = chkCut.Checked;
        //        pE00Ep.SetProcessBarCurrent = setSubPgbCurrent;
        //        pE00Ep.SetProcessBarMax = setSubPgbMax;
        //        // IScratchWorkspaceFactory pScratchWksFac = new ESRI.ArcGIS.DataSourcesGDB.FileGDBScratchWorkspaceFactory();
        //        // pE00Ep.TempFeatureWorkspace = pScratchWksFac.DefaultScratchWorkspace as IFeatureWorkspace;
        //        IFeatureWorkspace pFks = CreateGdbWks(System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location), "E00Temp.gdb");
        //        pE00Ep.TempFeatureWorkspace = pFks;
        //        if (pGeometry != null && chkCut.Checked)
        //        {
        //            pFclsClip = CreateClipFeatureClass(pE00Ep.TempFeatureWorkspace, pGeometry, (m_Application.Document as IMxDocument).ActiveView.FocusMap.SpatialReference);
        //        }
        //        progressBarAll.Value = 0;
        //        progressBarAll.Maximum = pLayers.Count;
        //        for (int i = 0; i < pLayers.Count; i++)
        //        {

        //            if (GP == null) GP = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
        //            GP.OverwriteOutput = true;
        //            GP.AddOutputsToMap = false;
        //            GP.LogHistory = true;
        //            pFeatureLayer = pLayers[i];
        //            IFeatureClass pFeatCls;
        //            pFeatCls = pFeatureLayer.FeatureClass;
        //            LogHelper.WriteLog("正在导出图层'" + pFeatureLayer.Name + "'");
        //            pE00Ep.FeatureLayer = pFeatureLayer;
        //            strTargetFileName = dataGridViewByMap.Rows[i].Cells[2].Value == null ? pFeatureLayer.Name : dataGridViewByMap.Rows[i].Cells[2].Value.ToString();
        //            strFilter = dataGridViewByMap.Rows[i].Cells[3].Value == null ? "" : dataGridViewByMap.Rows[i].Cells[3].Value.ToString();
        //            if (sptbctlGeo.SelectedTab == sptbitmSheet && chkEpByTufu.Checked)
        //            {
        //                System.Windows.Forms.Application.DoEvents();
        //                progressBarSub.Value = 0;
        //                progressBarSub.Maximum = _SheetCreator.CheckedSheets.Count;
        //                DirectoryInfo dir = new DirectoryInfo(txtExportPath.Text);
        //                for (int j = 0; j < _SheetCreator.CheckedSheets.Count; j++)
        //                {
        //                    LogHelper.WriteLog("开始导出图幅'" + _SheetCreator.CheckedSheets[j].Code + "'内的选择的图层数据");
        //                    if (chkCut.Checked)
        //                    {
        //                        pE00Ep.FeatureClassClip = CreateClipFeatureClass(pE00Ep.TempFeatureWorkspace, ((ESRI.ArcGIS.esriSystem.IClone)_SheetCreator.CheckedSheets[j].Geometry).Clone() as IGeometry, (m_Application.Document as IMxDocument).ActiveView.FocusMap.SpatialReference);
        //                    }
        //                    dir.CreateSubdirectory(_SheetCreator.CheckedSheets[j].Code);
        //                    pE00Ep.Path = txtExportPath.Text + "\\" + _SheetCreator.CheckedSheets[j].Code;
        //                    pE00Ep.FilterGeometry = _SheetCreator.CheckedSheets[j].Geometry;
        //                    pE00Ep.Filter = strFilter;
        //                    pE00Ep.TargetFileName = strTargetFileName;
        //                    if (pE00Ep.ExportMif(GP, pQuickEpTool))
        //                    {
        //                        LogHelper.WriteLog("图幅" + _SheetCreator.CheckedSheets[j].Code + "'内图层'" + pFeatureLayer.Name + "'导出成功");
        //                    }
        //                    else
        //                    {
        //                        LogHelper.WriteLog("图幅" + _SheetCreator.CheckedSheets[j].Code + "'内图层'" + pFeatureLayer.Name + "'导出失败");
        //                    }
        //                    // ((IDataset)pE00Ep.FeatureClassClip).Delete();
        //                    if (chkCut.Checked)
        //                    {
        //                        try
        //                        {
        //                            ((IDataset)pE00Ep.FeatureClassClip).Delete();
        //                            pE00Ep.FeatureClassClip = null;
        //                        }
        //                        catch (System.Exception) { }
        //                    }
        //                    progressBarSub.Value++;
        //                }

        //            }
        //            else
        //            {
        //                pE00Ep.FeatureClassClip = pFclsClip;
        //                pE00Ep.FilterGeometry = pGeometry;
        //                pE00Ep.Filter = strFilter;
        //                pE00Ep.TargetFileName = strTargetFileName;
        //                bool bln = pE00Ep.ExportMif(GP, pQuickEpTool);
        //                if (bln)
        //                {
        //                    LogHelper.WriteLog("图层'" + pFeatureLayer.Name + "'导出成功");
        //                }
        //                else
        //                {
        //                    LogHelper.WriteLog("图层'" + pFeatureLayer.Name + "'导出失败");
        //                }
        //                // ((IDataset)pE00Ep.FeatureClassClip).Delete();
        //            }

        //            progressBarAll.Value++;
        //            System.Windows.Forms.Application.DoEvents();
        //        }

        //        if (pE00Ep.FeatureClassClip != null)
        //        {
        //            try
        //            {
        //                ((IDataset)pE00Ep.FeatureClassClip).Delete();
        //                pE00Ep.FeatureClassClip = null;
        //            }
        //            catch (System.Exception) { }
        //        }
        //        //((IDataset)pFks).Delete();
        //        LogHelper.WriteLog("导出完毕");
        //        MsgHelper.ShowInfomationMsgbox("导出完毕！");
        //    }
        //    catch (System.Exception ex)
        //    {
        //        MsgHelper.ShowWarningMsgbox("导出失败：" + ex.Message);
        //    }
        //    finally
        //    {
        //        progressBarSub.Visible = false;
        //        progressBarAll.Visible = false;
        //        this.Cursor = Cursors.Default;
        //    }
        //}

        //private void ExportDwg_old()
        //{

        //    Autodesk.AutoCAD.Interop.IAcadApplication pAcadApplication = null;
        //    progressBarSub.Visible = true;
        //    progressBarAll.Visible = true;
        //    this.Enabled = false ;
        //    System.Diagnostics.Process pProcessNew = null;

        //    try
        //    {
        //        string strExePath;
        //        if (!DwgExportUtility.CheckCadInstall(out strExePath ))
        //        {
        //            MsgHelper.ShowWarningMsgbox("系统检测到您的电脑上未安装AutoCAD2007以上版本的软件！");
        //            return;
        //        }
        //        List<IFeatureLayer> pLayers = GetCheckLayers();
        //        if (pLayers.Count == 0)
        //        {
        //            MsgHelper.ShowInfomationMsgbox("未选择要导出的图层！");
        //            return;
        //        }

        //        this.Cursor = Cursors.WaitCursor;                
        //       // pAcadApplication = new Autodesk.AutoCAD.Interop.AcadApplicationClass();

        //        System.Diagnostics.Process[] pProcessCollection= System.Diagnostics.Process.GetProcessesByName("acad");

        //        System.Diagnostics.ProcessStartInfo pProcessInfo = new System.Diagnostics.ProcessStartInfo(strExePath);
        //        pProcessInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        //        System.Diagnostics.Process pCadProcess = System.Diagnostics.Process.Start(pProcessInfo);
        //        pCadProcess.WaitForInputIdle();
        //        System.Diagnostics.Process[] pProcessCollection2 = System.Diagnostics.Process.GetProcessesByName("acad");

        //        foreach (System.Diagnostics.Process p in pProcessCollection2)
        //        {
        //            bool blnFound = false;
        //            foreach (System.Diagnostics.Process p2 in pProcessCollection)
        //            {
        //                if (p.Id  == p2.Id )
        //                {
        //                    blnFound = true;
        //                    break;
        //                }
        //            }
        //            if (!blnFound)
        //            {
        //                pProcessNew = p;
        //                break;
        //            }
        //        }
        //        //while (pCadProcess.MainWindowHandle == IntPtr.Zero)
        //        //{
        //        //    System.Threading.Thread.Sleep(1000);
        //        //    pCadProcess.Refresh();
        //        //}

        //        while (pAcadApplication == null)
        //        {
        //            try
        //            {
        //                pAcadApplication = (Autodesk.AutoCAD.Interop.IAcadApplication)Marshal.GetActiveObject("AutoCAD.Application");
        //                System.Threading.Thread.Sleep(1000);
        //            }
        //            catch (Exception ex)
        //            {

        //                Application.DoEvents();
        //            }
        //        }



        //       // pAcadApplication = System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application.17") as Autodesk.AutoCAD.Interop.IAcadApplication;

        //       // object obj = System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application.17");
        //       // pAcadApplication.Visible = false;                       

        //        IFeatureLayer pFeatureLayer = null;
        //        string strFilter, strTargetFileName;
        //        List<IFeatureLayer> pFeatureLayerList = new List<IFeatureLayer>();
        //        List<string> pFilterList = new List<string>();
        //        for (int i = dataGridViewByMap.Rows.Count-1; i >=0; i--)
        //        {
        //            if (Convert.ToBoolean(dataGridViewByMap.Rows[i].Cells[0].Value) == true && dataGridViewByMap.Rows[i].Tag is IFeatureLayer)
        //            {
        //                pFeatureLayer = dataGridViewByMap.Rows[i].Tag as IFeatureLayer;
        //                pFeatureLayerList.Add(pFeatureLayer);
        //                strFilter = dataGridViewByMap.Rows[i].Cells[3].Value == null ? "" : dataGridViewByMap.Rows[i].Cells[3].Value.ToString();
        //                pFilterList.Add(strFilter);
        //            }                   
        //        }
        //        logPanel.ClearLog();

        //        E00DwgExport pE00DwgEp = new E00DwgExport();
        //        pE00DwgEp.CadFcodeTable = OpenCadFcodeTable();
        //        pE00DwgEp.Path = txtExportPath.ControlText;
        //        pE00DwgEp.Clip = chkCut.Checked;
        //        //IFeatureWorkspace pTmpWks = CreateGdbWks(System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location), "E00Temp.gdb");
        //        //pE00DwgEp.TempFeatureWorkspace = pTmpWks;
        //        pE00DwgEp.WriteLog = LogHelper.WriteLog;
        //        pE00DwgEp.SetProcessBarCurrent = setAllPgbCurrent;
        //        pE00DwgEp.SetProcessBarMax = setAllPgbMax;
        //        if (!chkAll.Checked)
        //        {
        //            if (tabControl2.SelectedTab.Text == "按图幅范围")
        //            {
        //                if (chooseTuFu2.TuFus.Count == 0)
        //                {
        //                    MsgHelper.ShowInfomationMsgbox("未选择图幅进行导出！");
        //                    return;
        //                }
        //                if (chkEpByTufu.Checked == false)
        //                {
        //                    LogHelper.WriteLog("开始导出选择的图幅范围内的选择的图层数据");
        //                    pE00DwgEp.FilterGeometry = TuFuUtility.GetSelectTuFuRegionByList(chooseTuFu2.TuFus);// UnionTfGeometry(chooseTuFu2.TuFus);                                             
        //                    pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //                    pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.ControlText);
        //                    pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //                }
        //                else
        //                {
        //                    progressBarAll.Value = 0;
        //                    progressBarAll.Maximum = chooseTuFu2.TuFus.Count;
        //                    foreach (TuFu pTufu in chooseTuFu2.TuFus)
        //                    {
        //                        LogHelper.WriteLog("开始导出图幅'" + pTufu.TuFuName + "'内的选择的图层数据");
        //                        pE00DwgEp.FilterGeometry = pTufu.Geometry;
        //                        if (System.IO.Directory.Exists(txtExportPath.ControlText))
        //                        {
        //                            pE00DwgEp.Path = txtExportPath.ControlText;
        //                        }
        //                        else
        //                        {
        //                            string strPath = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //                            if (System.IO.Directory.Exists(strPath ) == false)
        //                            {
        //                                LogHelper.WriteLog("导出路径设置不正确！");
        //                                return;
        //                            }
        //                            pE00DwgEp.Path = strPath;
        //                        }


        //                        pE00DwgEp.TargetFileName = pTufu.TuFuName;
        //                        pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //                        Application.DoEvents();
        //                        progressBarAll.Value++;
        //                    }
        //                }
        //            }
        //            else if (tabControl2.SelectedTab.Text == "按自定义范围")
        //            {
        //                if (pPolygonCustom == null)
        //                {
        //                    MsgHelper.ShowInfomationMsgbox("未定义范围进行导出！");
        //                    return;
        //                }
        //                LogHelper.WriteLog("开始导出自定义范围内的选择的图层数据");
        //                pE00DwgEp.FilterGeometry = pPolygonCustom;
        //                pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //                pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.ControlText);
        //                pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //            }
        //            else if (tabControl2.SelectedTab.Text == "按测区范围")
        //            {
        //                if (chooseFWX2.PolygonFWX == null)
        //                {
        //                    MsgHelper.ShowInfomationMsgbox("未选择测区范围进行导出！");
        //                    return;
        //                }
        //                LogHelper.WriteLog("开始导出选择的测区范围内的选择的图层数据");
        //                pE00DwgEp.FilterGeometry = chooseFWX2.PolygonFWX;
        //                pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //                pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.ControlText);
        //                pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //            }
        //            else if (tabControl2.SelectedTab.Text == "按行政区范围")
        //            {
        //                if (selectXZQ1.GetGeometry () == null)
        //                {
        //                    MsgHelper.ShowInfomationMsgbox("未选择行政区范围进行导出！");
        //                    return;
        //                }
        //                LogHelper.WriteLog("开始导出选择的行政区范围内的选择的图层数据");
        //                pE00DwgEp.FilterGeometry = selectXZQ1.GetGeometry();
        //                pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //                pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.ControlText);
        //                pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //            }
        //        }
        //        else
        //        {
        //            LogHelper.WriteLog("开始导出全图范围内的选择的图层数据");
        //            pE00DwgEp.FilterGeometry = null;
        //            pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.ControlText );
        //            pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.ControlText);
        //            pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //        }
        //        LogHelper.WriteLog("导出完毕");
        //        MsgHelper.ShowInfomationMsgbox("导出完毕！");
        //    }
        //    catch (System.Exception ex)
        //    {
        //        MsgHelper.ShowWarningMsgbox("导出失败：" + ex.Message);
        //    }
        //    finally
        //    {
        //        this.Enabled = true;
        //        progressBarSub.Visible = false ;
        //        progressBarAll.Visible = false ;
        //        this.Cursor = Cursors.Default;

        //        try
        //        {
        //            if (pAcadApplication != null)
        //            {

        //                pAcadApplication.Visible = true;
        //            }
        //            if (pProcessNew != null && pProcessNew.HasExited==false )
        //            {

        //                pProcessNew.Kill();
        //            }
        //        }
        //        catch (System.Exception) { }

        //    }

        //    SetCadVisible();
        //}
        //private void ExportDwg()
        //{           
        //    progressBarSub.Visible = true;
        //    progressBarAll.Visible = true;
        //    this.Enabled = false;
        //    DWGdirect.Runtime.Services cadService=null;
        //    try
        //    {               
        //        List<IFeatureLayer> pLayers = GetCheckLayers();
        //        if (pLayers.Count == 0)
        //        {
        //            MsgHelper.ShowInfomationMsgbox("未选择要导出的图层！");
        //            return;
        //        }
        //        this.Cursor = Cursors.WaitCursor;                               
        //        IFeatureLayer pFeatureLayer = null;
        //        string strFilter, strTargetFileName;
        //        List<IFeatureLayer> pFeatureLayerList = new List<IFeatureLayer>();
        //        List<string> pFilterList = new List<string>();
        //        for (int i = dataGridViewByMap.Rows.Count - 1; i >= 0; i--)
        //        {
        //            if (Convert.ToBoolean(dataGridViewByMap.Rows[i].Cells[0].Value) == true && dataGridViewByMap.Rows[i].Tag is IFeatureLayer)
        //            {
        //                pFeatureLayer = dataGridViewByMap.Rows[i].Tag as IFeatureLayer;
        //                pFeatureLayerList.Add(pFeatureLayer);
        //                strFilter = dataGridViewByMap.Rows[i].Cells[3].Value == null ? "" : dataGridViewByMap.Rows[i].Cells[3].Value.ToString();
        //                pFilterList.Add(strFilter);
        //            }
        //        }
        //        logPanel.ClearLog();
        //        cadService = new DWGdirect.Runtime.Services();
        //        E00DwgExport pE00DwgEp = new E00DwgExport();
        //        pE00DwgEp.CadFcodeTable = OpenCadFcodeTable();
        //        pE00DwgEp.Path = txtExportPath.ControlText;
        //        pE00DwgEp.Clip = chkCut.Checked;

        //        pE00DwgEp.WriteLog = LogHelper.WriteLog;
        //        pE00DwgEp.SetProcessBarCurrent = setAllPgbCurrent;
        //        pE00DwgEp.SetProcessBarMax = setAllPgbMax;
        //        if (!chkAll.Checked)
        //        {
        //            if (tabControl2.SelectedTab.Text == "按图幅范围")
        //            {
        //                if (chooseTuFu2.TuFus.Count == 0)
        //                {
        //                    MsgHelper.ShowInfomationMsgbox("未选择图幅进行导出！");
        //                    return;
        //                }
        //                if (chkEpByTufu.Checked == false)
        //                {
        //                    LogHelper.WriteLog("开始导出选择的图幅范围内的选择的图层数据");
        //                    pE00DwgEp.FilterGeometry = TuFuUtility.GetSelectTuFuRegionByList(chooseTuFu2.TuFus);// UnionTfGeometry(chooseTuFu2.TuFus);                                             
        //                    pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //                    pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.ControlText);
        //                    pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //                }
        //                else
        //                {
        //                    progressBarAll.Value = 0;
        //                    progressBarAll.Maximum = chooseTuFu2.TuFus.Count;
        //                    foreach (TuFu pTufu in chooseTuFu2.TuFus)
        //                    {
        //                        LogHelper.WriteLog("开始导出图幅'" + pTufu.TuFuName + "'内的选择的图层数据");
        //                        pE00DwgEp.FilterGeometry = pTufu.Geometry;
        //                        if (System.IO.Directory.Exists(txtExportPath.ControlText))
        //                        {
        //                            pE00DwgEp.Path = txtExportPath.ControlText;
        //                        }
        //                        else
        //                        {
        //                            string strPath = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //                            if (System.IO.Directory.Exists(strPath) == false)
        //                            {
        //                                LogHelper.WriteLog("导出路径设置不正确！");
        //                                return;
        //                            }
        //                            pE00DwgEp.Path = strPath;
        //                        }


        //                        pE00DwgEp.TargetFileName = pTufu.TuFuName;
        //                        pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //                        Application.DoEvents();
        //                        progressBarAll.Value++;
        //                    }
        //                }
        //            }
        //            else if (tabControl2.SelectedTab.Text == "按自定义范围")
        //            {
        //                if (pPolygonCustom == null)
        //                {
        //                    MsgHelper.ShowInfomationMsgbox("未定义范围进行导出！");
        //                    return;
        //                }
        //                LogHelper.WriteLog("开始导出自定义范围内的选择的图层数据");
        //                pE00DwgEp.FilterGeometry = pPolygonCustom;
        //                pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //                pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.ControlText);
        //                pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //            }
        //            else if (tabControl2.SelectedTab.Text == "按测区范围")
        //            {
        //                if (chooseFWX2.PolygonFWX == null)
        //                {
        //                    MsgHelper.ShowInfomationMsgbox("未选择测区范围进行导出！");
        //                    return;
        //                }
        //                LogHelper.WriteLog("开始导出选择的测区范围内的选择的图层数据");
        //                pE00DwgEp.FilterGeometry = chooseFWX2.PolygonFWX;
        //                pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //                pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.ControlText);
        //                pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //            }
        //            else if (tabControl2.SelectedTab.Text == "按行政区范围")
        //            {
        //                if (selectXZQ1.GetGeometry() == null)
        //                {
        //                    MsgHelper.ShowInfomationMsgbox("未选择行政区范围进行导出！");
        //                    return;
        //                }
        //                LogHelper.WriteLog("开始导出选择的行政区范围内的选择的图层数据");
        //                pE00DwgEp.FilterGeometry = selectXZQ1.GetGeometry();
        //                pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //                pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.ControlText);
        //                pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //            }
        //        }
        //        else
        //        {
        //            LogHelper.WriteLog("开始导出全图范围内的选择的图层数据");
        //            pE00DwgEp.FilterGeometry = null;
        //            pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //            pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.ControlText);
        //            pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //        }
        //        LogHelper.WriteLog("导出完毕");
        //        MsgHelper.ShowInfomationMsgbox("导出完毕！");
        //    }
        //    catch (System.Exception ex)
        //    {
        //        MsgHelper.ShowWarningMsgbox("导出失败：" + ex.Message);
        //    }
        //    finally
        //    {
        //        if (cadService != null) cadService.Dispose();
        //        this.Enabled = true;
        //        progressBarSub.Visible = false;
        //        progressBarAll.Visible = false;
        //        this.Cursor = Cursors.Default;              
        //    }          
        //}

        private void ExportDwgNew(string OutPath)  //WPY20151231
        {
            IFeatureLayer pFeatureLayer = null;
            string strFilter;
            List<IFeatureClass> pFeatureClassList = new List<IFeatureClass>();

            List<string> pFilterList = new List<string>();
            for (int i = dataGridViewByMap.Rows.Count - 1; i >= 0; i--)
            {
                if (Convert.ToBoolean(dataGridViewByMap.Rows[i].Cells[0].Value) == true && dataGridViewByMap.Rows[i].Tag is IFeatureLayer)
                {
                    pFeatureLayer = dataGridViewByMap.Rows[i].Tag as IFeatureLayer;
                    pFeatureClassList.Add(pFeatureLayer.FeatureClass);
                    strFilter = dataGridViewByMap.Rows[i].Cells[3].Value == null ? "" : dataGridViewByMap.Rows[i].Cells[3].Value.ToString();
                    pFilterList.Add(strFilter);
                }
            }
            if (pFeatureClassList.Count == 0)
            {
                MsgHelper.ShowInfomationMsgbox("请先选择要导出的图层！");
                return;
            } 
            try
            {
                _Export = new ExportCAD();
                _Export.FullName = OutPath;
                _Export.FeatureClasses = pFeatureClassList;
                _Export.IsClip = chkCut.Checked;
                _Export.HasMeta = false;
                _Export.HasTK = false;
                _Export.ProgressAll = new Progressor() { ProgressBar = progressBarAll };
                _Export.ProgressSub = new Progressor() { ProgressBar = progressBarSub };
                if (swtbtnAll.Value != true)
                {
                    if (sptbctlGeo.SelectedTab == sptbitmSheet)
                    {
                        if (_SheetCreator.CheckedSheets.Count == 0)
                        {
                            MsgHelper.ShowInfomationMsgbox("未选择图幅进行导出！");
                            return;
                        }
                        
                        if (chkEpByTufu.Checked == false)  //按合并图幅导出
                        {
                            _Export.ClipExtent = _SheetCreator.GetSelectGeometry();
                            //doing = true;
                            _Export.Export(false);
                        }
                        else      //按图幅分幅导出
                        {
                            _Export.Sheets = _SheetCreator.CheckedSheets;
                            //doing = true;
                            _Export.Export(true);
                        }
                    }
                    else if (sptbctlGeo.SelectedTab == sptbitmPoly)  //自定义范围导出
                    {
                        if (_ToolCreator.Geometry == null)
                        {
                            MsgHelper.ShowInfomationMsgbox("未定义范围进行导出！");
                            return;
                        }
                        LogHelper.WriteLog("开始导出自定义范围内的选择的图层数据");
                        _Export.ClipExtent = _ToolCreator.Geometry;
                        //doing = true;
                        _Export.Export(false);
                    }
                    else if (sptbctlGeo.SelectedTab == sptbitmArea)   
                    {
                        if (_AreaCreator.CheckedFeatures.Count == 0)
                        {
                            MsgHelper.ShowInfomationMsgbox("未选择测区范围进行导出！");
                            return;
                        }
                        if (chkEpByCeQu.Checked == false)   //按合并测区导出
                        {
                            LogHelper.WriteLog("开始导出选择的测区范围内的图层数据");
                            _Export.ClipExtent = _AreaCreator.GetSelectGeometry();
                            //doing = true;
                            _Export.Export(false);
                        }
                        else     //分测区导出
                        {
                            foreach (GridRow r in spgrdArea.PrimaryGrid.Rows)
                            {
                                if ((bool)r.Cells["colCheck"].Value == false) continue;
                                _Export.ClipExtent = ((IFeature)r.Tag).Shape;
                                _Export.FullName = OutPath +"\\"+ r.Cells["colName"].Value.ToString()+".dwg";
                                LogHelper.WriteLog("开始导出测区[" + r.Cells["colName"].Value.ToString() + "]范围内的数据...\n");
                                //doing = true;
                                _Export.Export(false);
                            }
                        }
                    }
                    else if (sptbctlGeo.SelectedTab == sptbitmRegion)    //行政区范围导出
                    {
                        if (regionTree.SelectedGeometry == null)
                        {
                            MsgHelper.ShowInfomationMsgbox("未选择行政区范围进行导出！");
                            return;
                        }
                        LogHelper.WriteLog("开始导出选择的行政区范围内的选择的图层数据");
                        _Export.ClipExtent = regionTree.SelectedGeometry;
                        //doing = true;
                        _Export.Export(false);
                    }
                }
                else    //全图导出
                {
                    LogHelper.WriteLog("开始导出全图范围内的选择的图层数据");
                    //doing = true;
                    _Export.Export(false);
                }
            }
            catch
            { }
        }


     

        private IFeatureWorkspace CreateGdbWks(string strPath, string strName)
        {
            IFeatureWorkspace pFks = null;
            IWorkspaceFactory2 pWksFac = new ESRI.ArcGIS.DataSourcesGDB.FileGDBWorkspaceFactoryClass();
            try
            {
                pFks = pWksFac.OpenFromFile(strPath + "\\" + strName, 0) as IFeatureWorkspace;
            }
            catch (System.Exception)
            {
                IWorkspaceName pWksName = pWksFac.Create(strPath, strName, null, 0);
                IName pName = pWksName as IName;
                pFks = pName.Open() as IFeatureWorkspace;
            }
            // IFileNames pFileNameS=new  FileNamesClass();
            //pFileNameS.Add( strName);
            //if (pWksFac.ContainsWorkspace(strPath, pFileNameS))
            //{
            //   IWorkspaceName pWksName= pWksFac.GetWorkspaceName(strPath, pFileNameS);
            //   IName pName = pWksName as IName;
            //   pFks = pName.Open() as IFeatureWorkspace;
            //}
            //else
            //{
            //    IWorkspaceName pWksName= pWksFac.Create(strPath, strName, null, 0);
            //    IName pName = pWksName as IName;
            //    pFks=pName.Open() as IFeatureWorkspace;
            //}
            return pFks;
        }

        /// <summary>
        /// 生成临时的裁切Featureclass
        /// </summary>
        /// <param name="pFwks"></param>
        /// <param name="pPolygon"></param>
        /// <param name="pSpatialRef"></param>
        /// <returns></returns>
        private IFeatureClass CreateClipFeatureClass(IFeatureWorkspace pFwks, IGeometry pPolygon, ISpatialReference pSpatialRef)
        {
            IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
            IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription;
            IFields fields = ocDescription.RequiredFields;
            int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName);
            IField field = fields.get_Field(shapeFieldIndex);
            IGeometryDef geometryDef = field.GeometryDef;
            IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
            geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
            geometryDefEdit.SpatialReference_2 = pSpatialRef;
            string strName = "clip";
            string strNewFclsName = strName;
            int index = -1;
            while (true)
            {
                index++;
                if (index == 0)
                {
                    strNewFclsName = strName;
                }
                else
                {
                    strNewFclsName = strName + "_" + index;
                }
                if (((IWorkspace2)pFwks).get_NameExists(esriDatasetType.esriDTFeatureClass, strNewFclsName) == false)
                {
                    break;
                }
            }
            pPolygon.Project(pSpatialRef);
            IFeatureClass pFcls = pFwks.CreateFeatureClass(strNewFclsName, fields, null, null, esriFeatureType.esriFTSimple, "SHAPE", "");
            IFeature pFeature = pFcls.CreateFeature();

            IZAware pZArare = pPolygon as IZAware;
            pZArare.ZAware = false;
            //IZ pZ = pPolygon as IZ;
            //if (pZ != null) pZ.SetConstantZ(0);

            pFeature.Shape = pPolygon;
            pFeature.Store();
            return pFcls;
        }

        #endregion

        /// <summary>
        /// 全图导出或按照范围导出控制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void swtbtnAll_ValueChanged(object sender, EventArgs e)
        {
            spgrdSheet.Enabled = !swtbtnAll.Value;
            spgrdArea.Enabled = !swtbtnAll.Value;
            regionTree.Enabled = !swtbtnAll.Value;
            if (swtbtnAll.Value == true)
            {
                chkCut.Checked = false;
                btnOpenFile.Enabled = false;
                btnDrawExtent.Enabled = false;
                chkEpByTufu.Enabled = false;
                chkEpByCeQu.Enabled = false;
            }
            else
            {
                chkEpByTufu.Enabled = sptbctlGeo.SelectedTab == sptbitmSheet;
                chkEpByCeQu.Enabled = sptbctlGeo.SelectedTab == sptbitmArea;
                btnOpenFile.Enabled = sptbctlGeo.SelectedTab == sptbitmArea;
                btnDrawExtent.Enabled = sptbctlGeo.SelectedTab != sptbitmArea;
            }
            chkCut.Enabled = !swtbtnAll.Value;
            if (breaked)
                txtExportPath.Text = ""; 
        }

        /// <summary>
        /// 比例尺选择改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbScale_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(cmbScale.Text)) return;
            if (_SheetCreator == null) return;
            _SheetCreator.ScaleValue = int.Parse(cmbScale.Text);
        }

        /// <summary>
        /// 打开测区范围面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            frmAddData.ShowDialog(this);
        }

        /// <summary>
        /// 切换选择范围方式时图面重绘范围
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sptbctlGeo_SelectedTabChanged(object sender, SuperTabStripSelectedTabChangedEventArgs e)
        {
            cmbScale.Visible = this.sptbctlGeo.SelectedTab == sptbitmSheet;
            if (swtbtnAll.Value == true) return;
            IGraphicsContainer pGraphicsContainer = (IGraphicsContainer)m_HookHelp.ActiveView;
            pGraphicsContainer.DeleteAllElements();
            if (this.sptbctlGeo.SelectedTab == sptbitmSheet && _SheetCreator.CheckedSheets != null)
            {
                _SheetCreator.ClearElement();
                _SheetCreator.DrawElements(_SheetCreator.CheckedSheets);
            }
            if (this.sptbctlGeo.SelectedTab == sptbitmArea && _AreaCreator.CheckedFeatures != null)
            {
                foreach (IElement ele in _AreaCreator.DrawElements)
                {
                    ElementHelper.AddElement(ele, m_pMap);
                }
            }
            if (this.sptbctlGeo.SelectedTab == sptbitmRegion && regionTree.DrawElements != null)
            {
                foreach (IElement ele in regionTree.DrawElements)
                {
                    ElementHelper.AddElement(ele, m_pMap);
                }
            }
            m_HookHelp.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics | esriViewDrawPhase.esriViewGeography, null, m_HookHelp.ActiveView.Extent);
            if (swtbtnAll.Value == false)
            {
                _ToolCreator.SetToolEnable("ToolDrawLine", (this.sptbctlGeo.SelectedTab == sptbitmSheet
                    ||this.sptbctlGeo.SelectedTab ==sptbitmRegion));
                chkEpByTufu.Enabled = this.sptbctlGeo.SelectedTab == sptbitmSheet;
                chkEpByCeQu.Enabled = this.sptbctlGeo.SelectedTab == sptbitmArea;
                btnOpenFile.Enabled = this.sptbctlGeo.SelectedTab == sptbitmArea;
                btnDrawExtent.Enabled = this.sptbctlGeo.SelectedTab != sptbitmArea;                
            }
        }

        /// <summary>
        /// 终止导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (!breaked)// && dlgDataImportByCode != null)
            {
                if (MsgHelper.ShowYesOrNoQueryMsgBox("是否要终止导出操作？") == DialogResult.Yes)
                {
                    if (dlgDataExportConstruct != null) dlgDataExportConstruct.Stop();
                    if (dlgDataExport != null) dlgDataExport.Stop();
                    if (_Export != null) _Export.Stop();
                    Application.DoEvents();
                    breaked = true;
                }
            }
        }

        private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Tag != null && (e.Node.Tag is IFeatureLayer))
            {

                IFeatureLayer pFeatLyr = e.Node.Tag as IFeatureLayer;

                foreach (DataGridViewRow dgvr in dataGridViewByMap.Rows)
                {
                    if (dgvr.Tag == null || !(dgvr.Tag is IFeatureLayer)) continue;

                    IFeatureLayer pFeatLyr2 = dgvr.Tag as IFeatureLayer;

                    if (pFeatLyr.Equals(pFeatLyr2))
                    {
                        tree = true;
                        dgvr.Cells[0].Value = e.Node.Checked;
                        tree = false;
                        return;
                    }
                }
            }
            
            if (!tree && !grid)
            {
                tree = true;
                TreeHelper.SetParentNodeState(e.Node);
                TreeHelper.CheckChildrenBySelf(e.Node, e.Node.Checked);
            }
            else
            {
                return;
            }

            tree = false;
        }

        private void dataGridViewByMap_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (this.dataGridViewByMap.RowCount == 0) return;
            if (e.ColumnIndex != 3) return;

            DataGridViewRow dgvR = this.dataGridViewByMap.Rows[e.RowIndex];

            if (dgvR.Tag != null && dgvR.Tag is IFeatureLayer)
            {
                FrmQueryByAttribute frmSQL = new FrmQueryByAttribute();

                frmSQL.Application = m_Application;
                frmSQL.FeatureLayerExp = (dgvR.Tag as IFeatureLayer);
                frmSQL.WhereCause = (dataGridViewByMap.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
                frmSQL.CmdOKClick = delegate(string sSQL)
                {
                    dataGridViewByMap.Rows[e.RowIndex].Cells[3].Value = sSQL;
                    dataGridViewByMap.RefreshEdit();
                };
                frmSQL.ShowDialog(this);
            }
        }

        private void dataGridViewByMap_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            //第一列复选框的值发生变化时，联动改变树节点的勾选情况
            if (e.ColumnIndex == 0)
            {
                //增加这句话，预防初始化时出错
                if ((dataGridViewByMap.Rows.Count == 0) || (e.RowIndex < 0)) return;

                if (dataGridViewByMap.Rows[e.RowIndex].Tag == null || !(dataGridViewByMap.Rows[e.RowIndex].Tag is IFeatureLayer)) return;

                IFeatureLayer pFeatLyr = dataGridViewByMap.Rows[e.RowIndex].Tag as IFeatureLayer;

                List<TreeNode> treeNodes = TreeHelper.GetAllYzTreeNode2(treeView1.Nodes[0]);

                foreach (TreeNode treeNode in treeNodes)
                {
                    if (treeNode.Tag == null || !(treeNode.Tag is IFeatureLayer)) continue;

                    IFeatureLayer pFeatLyr2 = treeNode.Tag as IFeatureLayer;
                    if (pFeatLyr.Equals(pFeatLyr2))
                    {
                        grid = true;

                        treeNode.Checked = (bool)dataGridViewByMap.Rows[e.RowIndex].Cells[0].Value;

                        TreeHelper.CheckChildrenBySelf(treeNode, treeNode.Checked);
                        TreeHelper.SetParentNodeState(treeNode);

                        grid = false;

                        return;
                    }
                }
            }
        }

        private void dataGridViewByMap_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                ContextMenuStrip pContextMenu = new ContextMenuStrip();
                ToolStripMenuItem pItemSelectAll = new ToolStripMenuItem("全选");
                pItemSelectAll.Enabled = dataGridViewByMap.Rows.Count > 0;
                pContextMenu.Items.Add(pItemSelectAll);
                ToolStripMenuItem pItemUnSelectAll = new ToolStripMenuItem("全不选");
                pItemUnSelectAll.Enabled = dataGridViewByMap.Rows.Count > 0;
                pContextMenu.Items.Add(pItemUnSelectAll);

                ToolStripMenuItem pItemCheckSelectAll = new ToolStripMenuItem("选中项勾选");
                pItemUnSelectAll.Enabled = dataGridViewByMap.Rows.Count > 0;
                pContextMenu.Items.Add(pItemCheckSelectAll);

                ToolStripMenuItem pItemUnCheckSelectAll = new ToolStripMenuItem("选中项不勾选");
                pItemUnSelectAll.Enabled = dataGridViewByMap.Rows.Count > 0;
                pContextMenu.Items.Add(pItemUnCheckSelectAll);

                pItemSelectAll.Click += new EventHandler(pItemSelectAll_Click);
                pItemUnSelectAll.Click += new EventHandler(pItemUnSelectAll_Click);
                pItemCheckSelectAll.Click += new EventHandler(pItemCheckSelectAll_Click);
                pItemUnCheckSelectAll.Click += new EventHandler(pItemUnCheckSelectAll_Click);

                pContextMenu.Show(this.dataGridViewByMap, e.X, e.Y);

            }
            else if (e.Button == MouseButtons.Left)
            {
                //this.dataGridViewByMap.CurrentRow.Cells[0].Value = false;
            }
        }

        /// <summary>
        /// 单击闪烁
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void spgrdArea_RowClick(object sender, GridRowClickEventArgs e)
        {
            //_AreaCreator.FlashSelected();
        }
        
       
        /// <summary>
        /// 双击定位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void spgrdArea_RowDoubleClick(object sender, GridRowDoubleClickEventArgs e)
        {
            _AreaCreator.ZoomToSelected();
            _AreaCreator.FlashSelected();
        }

        /// <summary>
        /// 全选测区
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelAllArea_Click(object sender, EventArgs e)
        {
            _AreaCreator.Select(selType.All);
        }

        /// <summary>
        /// 全不选测区
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNoSelArea_Click(object sender, EventArgs e)
        {
            _AreaCreator.Select(selType.NONE);
        }

        /// <summary>
        /// 反选测区
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReverSelArea_Click(object sender, EventArgs e)
        {
            _AreaCreator.Select(selType.REVERSE);
        }

        /// <summary>
        /// 全选图幅
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelAllSheet_Click(object sender, EventArgs e)
        {
            foreach (GridRow r in spgrdSheet.PrimaryGrid.Rows)
            {
                if ((bool)r.Cells["colCheck"].Value == false)
                {
                    r.Cells["colCheck"].Value = true;
                    Mapsheet sheet = r.Tag as Mapsheet;
                    int idx=_SheetCreator.AllSheets.FindIndex(t => t.Code == sheet.Code);
                    if(idx > -1)
                    {
                        if(_SheetCreator.AllSheets[idx].Checked==false) 
                            _SheetCreator.AllSheets[idx].Checked=true;
                    }                    
                }
            }
            _SheetCreator.ClearElement();
            _SheetCreator.DrawElements(_SheetCreator.CheckedSheets);
        }

        /// <summary>
        /// 全不选图幅
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNoSelSheet_Click(object sender, EventArgs e)
        {
            foreach (GridRow r in spgrdSheet.PrimaryGrid.Rows)
            {
                if ((bool)r.Cells["colCheck"].Value == true)
                {
                    r.Cells["colCheck"].Value = false;
                    Mapsheet sheet = r.Tag as Mapsheet;
                    int idx = _SheetCreator.AllSheets.FindIndex(t => t.Code == sheet.Code);
                    if (idx > -1)
                    {
                        if (_SheetCreator.AllSheets[idx].Checked == true)
                            _SheetCreator.AllSheets[idx].Checked = false;
                    }
                }
            }
            _SheetCreator.ClearElement();
            _SheetCreator.DrawElements(_SheetCreator.CheckedSheets);
        }

        /// <summary>
        /// 反选图幅
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReverSelSheet_Click(object sender, EventArgs e)
        {
            foreach (GridRow r in spgrdSheet.PrimaryGrid.Rows)
            {
                if ((bool)r.Cells["colCheck"].Value == true)
                {
                    r.Cells["colCheck"].Value = false;
                    Mapsheet sheet = r.Tag as Mapsheet;
                    int idx = _SheetCreator.AllSheets.FindIndex(t => t.Code == sheet.Code);
                    if (idx > -1)
                    {
                        if (_SheetCreator.AllSheets[idx].Checked == true)
                            _SheetCreator.AllSheets[idx].Checked = false;
                    }
                }
                else if ((bool)r.Cells["colCheck"].Value == false)
                {
                    r.Cells["colCheck"].Value = true;
                    Mapsheet sheet = r.Tag as Mapsheet;
                    int idx = _SheetCreator.AllSheets.FindIndex(t => t.Code == sheet.Code);
                    if (idx > -1)
                    {
                        if (_SheetCreator.AllSheets[idx].Checked == false)
                            _SheetCreator.AllSheets[idx].Checked = true;
                    }
                }
            }
            _SheetCreator.ClearElement();
            _SheetCreator.DrawElements(_SheetCreator.CheckedSheets);
        }

        /// <summary>
        /// 导出名称标识字段切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbFields_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (GridRow r in spgrdArea.PrimaryGrid.Rows)
            {
                IFeature pFeature=r.Tag as IFeature;
                string name=pFeature.get_Value(pFeature.Fields.FindField(cmbFields.Text)).ToString();
                if (String.IsNullOrWhiteSpace(name))
                {
                    string id = pFeature.get_Value(pFeature.Fields.FindField("OBJECTID")).ToString();
                    r.Cells["colName"].Value = id;
                    LogHelper.WriteLog("ID为[" + id + "]的面要素[" + cmbFields.Text + "]字段属性为空，使用OID作为导出标识名称。");
                }                    
                else
                    r.Cells["colName"].Value = name;
            }
            _AreaCreator.m_nameField = cmbFields.Text;
        }

        private void dataGridViewByMap_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0)//单击复选框时  
            {
                dataGridViewByMap.CurrentCell = dataGridViewByMap.Rows[e.RowIndex].Cells[1];
                //this.dataGridViewByMap.CurrentCell.Value = !Convert.ToBoolean(this.dataGridViewByMap.CurrentCell.Value);
            }  
        }

        private void chkEpByTufu_CheckedChanged(object sender, CheckBoxChangeEventArgs e)
        {
            if(breaked)
                txtExportPath.Text = "";            
        }

        private void chkEpByCeQu_CheckedChanged(object sender, CheckBoxChangeEventArgs e)
        {
            if (breaked)
                txtExportPath.Text = ""; 
        }

        private void cboType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboType.SelectedIndex == 0 || cboType.SelectedIndex == 1 || cboType.SelectedIndex == 2)
            {                
                chkAddResult.Enabled = true;
                chkUseGP.Enabled = true;
            }
            else
            {
                chkAddResult.Checked = false;
                chkAddResult.Enabled = false;
                chkUseGP.Checked = false;
                chkUseGP.Enabled = false;
            }
            if(breaked)
                txtExportPath.Text = "";            
        }

        private void dataGridViewByMap_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            //dataGridViewByMap.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }
    }
}
